Skip to content

Instantly share code, notes, and snippets.

@joshnesbitt
Created February 19, 2010 15:52
Show Gist options
  • Select an option

  • Save joshnesbitt/308813 to your computer and use it in GitHub Desktop.

Select an option

Save joshnesbitt/308813 to your computer and use it in GitHub Desktop.
module Configuration
def self.attributes
@attributes
end
def self.configure
base = ConfigBlock.new
yield base
@attributes = base.attrs
end
def self.[](value)
self.attributes[value]
end
def self.method_missing(method, *args, &block)
puts method
self.attributes[method]
end
class ConfigBlock
attr_accessor :attrs
def initialize(attrs = {})
@attrs = attrs
end
def method_missing(method, *args, &block)
name = method.to_s.sub('=','').to_sym#Take the = off the end
#If is's a method like foo= then assign it to the internal structure
if(method.to_s.include?('='))
attrs[name] = args[0]
else
#Otherwise it's a sub-block that you should store a reference to the actual created attributes
sub_block = ConfigBlock.new
@attrs[name] = sub_block.attrs
sub_block # then return the sub_block magician so that it can continue to get at the further nested attributes
end
end
end
end
Configuration.configure do |top|
top.bottom = "hi"
top.left.right = "this is right"
top.some.other.variable.name = "a name"
end
puts Configuration[:bottom]
puts Configuration[:left][:right]
puts Configuration[:some][:other][:variable][:name]
puts Configuration.some[:other][:variable][:name]
puts Configuration.some.other.variable.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment