I Don't Feel Like It, Why Don't You
January 23rd, 2007
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”
Sorry, comments are closed for this article.

January 25th, 2007 at 02:01 PM
Nice. Delegate looks to be very useful. Thanks for the tip!
January 27th, 2007 at 10:04 AM
so,
class klass delegate :inbox, :to => :actions end
means; klass.actions.inbox ??
why :through doesn’t work here?
January 29th, 2007 at 02:58 PM
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.
January 30th, 2007 at 06:23 PM
@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.
February 20th, 2007 at 12:30 AM
http://quotedprintable.com/2006/12/22/delegation-and-demeter-in-rails ... is the correct url for “Delegation and Demeter in Rails”