Delegating methods to other objects is often helpful but the syntax of both
def_delegators
Show archive.org snapshot
and
def_delegator
Show archive.org snapshot
is a complete mess that makes your code hard to read.
Consider these classes:
class Topic < ActiveRecord::Base
def title
"A title"
end
def category
"Topic category"
end
end
class Post < ActiveRecord::Base
belongs_to :topic
def_delegators :topic, :title, :category
end
Here, we can say Post.new.title and actually read title from the Post's Topic object. Because of what we defined for Post, this also works for the category -- and the code gets even more unreadable to more attributes you delegate.
Alternative to def_delegators
When working with Rails, use delegate ... :to => ... instead:
class Post < ActiveRecord::Base
belongs_to :topic
delegate :title, :category, :to => :topic
end
That's a lot prettier!
See the
documentation
Show archive.org snapshot
for more examples and how to use delegate for even more (like delegating to constants).
Alternative to def_delegator
Now, consider this class definition, where we can say Post.new.subject which actually reads the associated Topic's title:
class Post < ActiveRecord::Base
belongs_to :topic
def_delegator :topic, :title, :subject
end
Looks a lot like the above def_delegators call but behaves differently.
Rails does not provide a pretty solution to this, but simply write a method for it and everybody knows what you are trying to do:
class Post < ActiveRecord::Base
belongs_to :topic
def subject
topic.title
end
end