on programming Rails for fun and profit...

Configure Classes Using the Configurable Concern in Rails

Sometimes, you need a config-like property on a class, such as a logger. Rails provides a `Configurable` concern that lets you accomplish this. It provides a config method that allows you to access (read and write) configuration options using the method-like syntax.

class Invoice
  include ActiveSupport::Configurable
  
  config_accessor :type
end

Invoice.type # => nil
Invoice.type = :cheque
Invoice.type # => :cheque

A nice benefit of using Configurable is that all the instances get the same config option, which they can override independently without affecting the class config.

invoice = Invoice.new
invoice.type # => :cheque

invoice.type = :credit
invoice.type # => :credit

Invoice.type # => :cheque
new_invoice = Invoice.new
new_invoice.type # => :cheque

Behind the scenes, the config method returns an instance of OrderedOptions class. To learn more, check out my article on ordered options.

How to Access Hash Values Like Methods using OrderedOptions
In Ruby, if you want to access hash values like methods on an object, use ActiveSupport::OrderedOptions. This class inherits from Hash and provides dynamic accessor methods. Typically, you’d do this with a Hash. person = { name: “Jason”, company: “Basecamp”} person[:company] # ‘Basecamp’ U…

Practical Use

Rails uses the Configurable concern to add  logger configuration option on the controllers.

The AbstractController::Base class includes this concern so you can configure a logger on the controllers.

# actionpack/lib/abstract_controller/base.rb

require "active_support/configurable"

module AbstractController
  class Base
    include ActiveSupport::Configurable

    # rest of the code
    end
  end
end

Then the AbstractController::Logger module (concern) configures the :logger config on the controllers.

# actionpack/lib/abstract_controller/logger.rb

module AbstractController
  module Logger
    extend ActiveSupport::Concern

    included do
      config_accessor :logger
    end
  end
end

This allows you to configure loggers on your controllers, as well as access them whenever needed.

To learn more about concerns and how they work, check out this detailed article.

Concerns in Rails: Everything You Need to Know
Concerns are an important concept in Rails that can be confusing to understand for those new to Rails as well as seasoned practitioners. This post explains why we need concerns, how they work, and how to use them to simplify your code.

Subscribe to Akshay's Blog

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe