Skip to content

Instantly share code, notes, and snippets.

@joshnesbitt
Created January 21, 2010 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save joshnesbitt/283299 to your computer and use it in GitHub Desktop.
Save joshnesbitt/283299 to your computer and use it in GitHub Desktop.
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
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