04 June 2012

ActiveSupport::Configurable, which is part of ActiveSupport in Rails, gives objects the ability to store configuration options.

Here’s how you can use it to augment an object with configuration options.

class Employee
  include ActiveSupport::Configurable

employee = Employee.new
employee.config.research_lab_entry = :not_allowed
employee.config.paid_leave = 5

When a config option that has not been set is requested, it’ll return nil. That’s because internally, the config options are stored in an OrderedHash which is another cool class that ActiveSupport provides.

To make the config options available as methods on the object itself, use the config_accessor method to specify a list.

class Employee
  include ActiveSupport::Configurable
  config_accessor :research_lab_entry, :paid_leave
  # The config options are now also available as: 
  # employee.research_lab_entry
  # employee.paid_leave

In the above example, the config options are being set at the object-level. And each object can have it’s own set of config. If you set them at the class-level, then they are shared. Like the example below:

# Set the config option at the class level
Employee.config.paid_leave = 5

# Create a new object and check the value
employee = Employee.new
employee.config.paid_leave # => 5

# Set a new value at the object-level
employee.config.paid_leave = 3

# Now check the value at the class level
Employee.config.paid_leave # => 3

If you are using this outside of Rails, you should have the “activesupport” gem installed and require “active_support/configurable” in your code.

Update: For more functionality Ken Collins has authored a gem store_configurable.

blog comments powered by Disqus