January 24, 2007

Posted by John

Older: A Handy Use Of to_s

Newer: I can mount my ssh where?

I Don't Feel Like It, Why Don't You

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 Comments

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

  2. so,

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

    means; klass.actions.inbox ??

    why :through doesn’t work here?

  3. 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. @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. 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 to ease the burden of pruning spam.

About

Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.

Projects

Flipper
Release your software more often with fewer problems.
Flip your features.