Read more

Nicer alternatives to def_delegator or def_delegators

Arne Hartherz
February 22, 2012Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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
Posted by Arne Hartherz to makandra dev (2012-02-22 11:01)