Dead Simple Delegation in Rails

I can't believe I didn't see this when it came out. Instead of this:

class Child < ActiveRecord::Base
  belongs_to :parent

  def parent_name
    parent.name
  end
end

Or this:

require 'forwardable'
class Child < ActiveRecord::Base
  extend Forwardable

  belongs_to :parent
  def_delegator :parent, :name, :parent_name
end

You can now do this (as of Rails 2.2.2)

class Child < ActiveRecord::Base
  belongs_to :parent
  delegate :name, :to => :parent, :prefix => true
end

Check out some more detailed examples in the documentation

blog comments powered by Disqus