Forum: Ruby on Rails [:year, :month, :day].each { |m| delegate m, :to => :publish

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
934f858e451cf9b771996b2940cd696b?d=identicon&s=25 Raj Singh (dorelal)
on 2007-01-01 07:38
(Received via mailing list)
Given below is a model from mephisto blogging tool.

class Content < ActiveRecord::Base
  filtered_column :body, :excerpt
  belongs_to :user, :with_deleted => true
  belongs_to :site
  [:year, :month, :day].each { |m| delegate m, :to => :published_at }

I couldn't understand the last line.

Anyone care to explain what's happening in the last line.

- Neeraj
F01c3ff32fee35d911e81c172a005012?d=identicon&s=25 Tom Fakes (Guest)
on 2007-01-01 08:52
(Received via mailing list)
This is the quick way of writing the following:

  def year

  def year=(y)
    published_at.year = y

  # Same for month and day

The 'delegate' method allows you to delegate a member access to a
member with the same name on a different member object, so you can
avoid writing 'content.published_at.year'
D8cb8c8cd40ddf0cd05241443a591868?d=identicon&s=25 Duane Johnson (Guest)
on 2007-01-01 17:45
(Received via mailing list)
Thanks, Tom, that's really handy.

I was wondering where this 'delegate' method is defined, so I looked
it up and found it in ActiveSupport--it's a method defined in the
Module class.  Pretty tricky :)

Available here, if anyone else is interested:

Duane Johnson
This topic is locked and can not be replied to.