Delegate is a pretty sweet method. Have you used it yet? Let’s say you have:

class User < ActiveRecord::Base
  has_many :actions
end

class Action < ActiveRecord::Base
  belongs_to :user

  class << self
    def inbox
      find(:all, :conditions => ['inbox = 1'])
    end
  end
end

To access a users inbox actions you would have to:

user = User.find(1)
user.actions.inbox

This isn’t bad, but let’s throw delegate into the mix like so:

class User < ActiveRecord::Base
  has_many :actions

  delegate :inbox, :to => :actions
end

class Action < ActiveRecord::Base
  belongs_to :user

  class << self
    def inbox
      find(:all, :conditions => ['inbox = 1'])
    end
  end
end

Now you can access a user’s inbox actions like this:

user = User.find(1)
user.inbox # instead of user.actions.inbox

Just like the title of this article, the User model says I don’t feel like dealing with the inbox method so why don’t you deal with it Action. Saves some keystrokes and it just feels right.

Related Reads

5 Responses to “I Don't Feel Like It, Why Don't You”

  1. Robert Says:

    Nice. Delegate looks to be very useful. Thanks for the tip!

  2. inanc Says:

    so,

    class klass delegate :inbox, :to => :actions end

    means; klass.actions.inbox ??

    why :through doesn’t work here?

  3. Danger Says:

    It should be pointed out that this doesn’t work on Ruby 1.8.2. All the more reason for folks to update to 1.8.5.

  4. John Nunemaker Says:

    @inanc – :through is for join models. Inbox is not a model. It is a class method in Action. It doesn’t join to models together. Rather, it just forwards a method call to another class.

    @Danger – Thanks for pointing that out.

  5. nicolash Says:

    http://quotedprintable.com/2006/12/22/delegation-and-demeter-in-rails ... is the correct url for “Delegation and Demeter in Rails”

Sorry, comments are closed for this article.