Skip to content

Instantly share code, notes, and snippets.

@jamesmoriarty
Created March 27, 2012 02:31
Show Gist options
  • Save jamesmoriarty/2211944 to your computer and use it in GitHub Desktop.
Save jamesmoriarty/2211944 to your computer and use it in GitHub Desktop.
Ruby Object Configuration Block
1.9.2p290 :083 > MyObject.configure do |config|
1.9.2p290 :084 > config.logger = STDOUT
1.9.2p290 :085?> end
=> MyObject
1.9.2p290 :190 > MyObject.new
=> #<MyObject:0x000001009ae268 @logger=#<IO:<STDOUT>>>
1.9.2p290 :191 > MyObject.new(:logger => nil)
=> #<MyObject:0x000001009a6928 @logger=nil>
class MyObject
VALID_ATTRIBUTE_KEYS = [:logger]
def initialize(attributes={})
attributes = MyObject.config.merge(attributes)
MyObject::VALID_ATTRIBUTE_KEYS.each do |key|
instance_variable_set("@#{key}", attributes[key])
end
end
class << self
attr_accessor :logger
def configure
yield self
self
end
def defaults
{:logger => nil}
end
def config
attributes = defaults
VALID_ATTRIBUTE_KEYS.each do |key|
attributes[key] = send(key) if send(key)
end
attributes
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment