Created
March 27, 2012 02:31
-
-
Save jamesmoriarty/2211944 to your computer and use it in GitHub Desktop.
Ruby Object Configuration Block
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
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> |
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
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