Skip to content

Instantly share code, notes, and snippets.

@ceilingfish
Created February 8, 2010 17:04
Show Gist options
  • Save ceilingfish/298354 to your computer and use it in GitHub Desktop.
Save ceilingfish/298354 to your computer and use it in GitHub Desktop.
class Mash < Hash
def method_missing(method_name, *args, &block)
self[method_name]
end
end
module Configuration
def self.attributes
@attributes
end
def self.configure
base = ConfigBlock.new
yield base
@attributes = {} if @attributes.nil?
@attributes.merge!(base.attrs)
end
def self.[](name)
attributes[name]
end
class ConfigBlock
attr_accessor :attrs
def initialize(attrs = Mash.new)
@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
def self.method_missing(method_name, *args, &block)
@attributes[method_name]
end
end
Configuration.configure do | top |
top.first_block = "One"
end
Configuration.configure do | top |
top.second.block = 2
end
puts Configuration.first_block
puts Configuration.second.block
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment