ActiveSupport hidden gems

Even though Rails, as any open source project, lacks some documentation, its source code is open so we’d be fool not to dig in it !

Here are a couple of my findings in the not so publicly documented ActiveSupport source code.

Class attribute inheritance

Ever wanted to create an attribute on a base class that is not shared among its subclasses ?

Sadly @@my_var won’t work, as it will create a class variable shared by all classes
in the inheritance tree. ActiveSupport to the rescue!

class Room
  class_inheritable_accessor :cookies_eaten

class Kitchen < Room; end
class BedRoom < Room; end

Kitchen.cookies_eaten = 3
BedRoom.cookies_eaten = 1
Kitchen.cookies_eaten != BedRoom.cookies_eaten

write_inheritable_attribute and read_inheritable_attribute are also really useful in included modules to create variables belonging to the actual class. This is commonly used in Rails macro, for example, controller filters declaration.

Others hidden gems


Encapsulates the around pattern, adding behaviour to a method without altering it, which is equivalent to:

alias_method :foo_without_feature, :foo
alias_method :foo, :foo_with_feature
Module#mattr_accessor, Class#cattr_accessor

Like attr_accessor but for module and class variables. Comes also in reader and writer flavours.


Encapsulates the delegator pattern. So rather then:

def hello


delegate :hello, :to => :greeter



A Ruby-ized realization of the K combinator

def foo
  returning values = [] do
    values << 'bar'
    values << 'baz'

foo # => ['bar', 'baz']

Turns the symbol into a simple proc, which is especially useful for enumerations.

# The same as people.collect { |p| }

# The same as { |p| p.manager? }.collect { |p| p.salary }

Converts an array to comma-seperated sentence where the last element is joined by the connector word.

%w(MacBook Guru Rock'n'roll).to_sentence # => "MacBook, Guru, and Rock'n'roll"

Have you found anything else of interest inside the mysterious ActiveSupport ?



Filed under rails, ruby

2 responses to “ActiveSupport hidden gems

  1. jamesgolick

    How many times have you written this snippet, to get an options hash out of the last parameter of a methods arguments?

    def some_method(*args)
    opts = args.pop if args.last.is_a? Hash


    Well, now (as of about 5 minutes ago), in edge rails, you can just say:

    def some_method(*args)
    opts = args.extract_options!

  2. Nice shortcut James!

    Look at this one in the migration generator, committed just before:

    Amazing the improvements made everyday!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s