Created
January 21, 2010 22:55
-
-
Save joshnesbitt/283299 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'yaml' | |
module Config | |
class << self | |
def configure(file_or_yaml=nil) | |
@@configuration ||= {} | |
if file_or_yaml | |
@@configuration = File.exists?(file_or_yaml) ? YAML.load_file(file_or_yaml) : YAML.load(file_or_yaml) | |
end | |
yield(self) if block_given? | |
end | |
def method_missing(method, *args) | |
method = method.to_s | |
case | |
when method.to_s.include?("=") # make this better (regex) | |
@@configuration[method.to_s.gsub("=", "")] = args.first if args.first | |
when (value = @@configuration[method]) | |
value | |
else | |
# Here we can either raise no_method for Object or nil... | |
# super(method.to_sym, *args) | |
nil | |
end | |
end | |
end | |
end | |
# Standalone (without YAML) | |
Config.configure do |config| | |
config.example_one = "One" | |
config.example_two = "Two" | |
end | |
puts Config.example_one | |
puts Config.example_two | |
puts Config.doesnt_exist | |
# With YAML (inline) | |
yaml = <<CONTENT | |
example_one: "Oooooo" | |
example_two: "It loads from YAML too!" | |
CONTENT | |
Config.configure(yaml) | |
puts Config.example_one | |
puts Config.example_two | |
# With YAML (file) | |
Config.configure("config.yml") | |
puts Config.example_one | |
puts Config.example_two | |
# Or go nuts (inline yaml and block) | |
yaml = <<CONTENT | |
example_three: "Oooooo" | |
example_four: "It loads from YAML too!" | |
CONTENT | |
Config.configure(yaml) do |config| | |
config.example_one = "One" | |
config.example_two = "Two" | |
end | |
puts Config.example_one | |
puts Config.example_two | |
puts Config.example_three | |
puts Config.example_four |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
example_one: "YAMLLY" | |
example_two: "YAMLLY AHA" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment