Skip to content

Instantly share code, notes, and snippets.

@sbellware
Created September 21, 2011 16:05
Show Gist options
  • Select an option

  • Save sbellware/1232480 to your computer and use it in GitHub Desktop.

Select an option

Save sbellware/1232480 to your computer and use it in GitHub Desktop.
Sketches of Configuration API
class Thing
include Configured
setting :some_setting
setting :other_setting
end
class Configuration
def some_setting
'foo'
end
def other_setting
'bar'
end
end
# Example 1: Configuring with explicit config object
config = Configuration.new
thing = Thing.new
thing.configure(config)
thing.some_setting # => 'foo'
thing.other_setting # => 'bar'
# Example 2: Configuring with default config object
thing = Thing.new
thing.configure # no arg. raises an error.
# add 'default' method to configuration object
class Configuration
def default
self.instance # or whatever means of getting an instance
end
end
thing = Thing.new
thing.configure # uses Configuration.default
# Example 3: Get setting names
Thing.settings # => [:some_setting, :other_setting]
# Example 4: Get settings
thing = Thing.new
thing.settings # => { :some_setting => nil, :other_setting => nil }
thing.configure
thing.settings # => { :some_setting => 'foo', :other_setting => 'bar' }
# Example 5: Change the configuration source
class SomeConfiguration
def other_setting
'blah'
end
end
class Thing
include Configured
configuration SomeConfiguration
setting :some_setting
setting :other_setting
end
thing = Thing.new
thing.configure
thing.other_setting # => 'blah'
# Example 6: Use the configuration API directly
class OtherConfiguration
def other_setting
'blaz'
end
end
thing = Thing.new
config = OtherConfiguration.new # or whatever means of creating an instance
config.configure(thing)
thing.some_setting # => nil # provides (pushes) only those values it knows about
thing.other_setting # => 'blaz'
# Example 7: Errors when object cannot be completely configured when pulling settings from a configuration object
class FooConfiguration
def some_setting
'foo'
end
end
class Thing
include Configured
configuration FooConfiguration
setting :some_setting
setting :other_setting
end
# Example 8: Configuring with explicit config object
thing = Thing.new
thing.configure
# => Configuration Error, "'other_setting' is not configured'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment