Dynamically Define Attribute Readers with Ruby

attr_reader is a handy method to dynamically define attribute readers without manually defining each ‘boilerplate’ method. This post shows how to use metaprogramming to dynamically define attribute reader methods without using the built-in attr_reader method. Specifically, we would like to add a readers() method to the Object class so methods to read instance variable values are automatically available.

class Person
  readers(:first_name, :last_name)

  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
  end
end

b = Person.new('b', 'l')
p b.first_name # => 'b'
p b.last_name # => 'l'

readers() must be a class method and take one or more arguments. readers() should dynamically define methods that correspond with the argument names.

class Object
  def self.readers(*args)
    args.each do |arg|
      define_method(arg) {
        instance_variable_get("@#{arg.to_s}")
      }
    end
  end
end

The readers() method iterates over every argument, defines a method corresponding with the argument name, and gets the value of an instance variable associated with the argument name. attr_reader is a great example of how metaprogramming can be used to defined methods at runtime to avoid writing tedious or redundant code.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s