January 24, 2007
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.
5 Comments
Jan 25, 2007
Nice. Delegate looks to be very useful. Thanks for the tip!
Jan 27, 2007
so,
class klass
delegate :inbox, :to => :actions
end
means; klass.actions.inbox ??
why :through doesn’t work here?
Jan 29, 2007
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.
Jan 30, 2007
@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.
Feb 20, 2007
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.