Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Allow overriding a delegation

#1720

This patch allows you to override the delegation, providing your own value.


class Name < Struct.new(:first, :last)
  def display_name
    "#{first} #{last}"
  end
end

class Person < Struct.new(:name)
  delegate :display_name, :to => :name, :allow_override => true
end
  
david = Person.new(:name => Name.new("David", "Hansson"))
david.display_name  #=> "David Hansson"
david.display_name = "DHH"
david.display_name  #=> "DHH"

I've found uses for this in my own applications:


class Residentship < ActiveRecord::Base
  belongs_to :resident
  validates_presence_of :room_number, :moved_out_at
end

class Resident < ActiveRecord::Base
  has_many :residentships
  has_one :current_residentship,
    :class_name => "Residentship",
    :conditions => "moved_out_at IS NULL"
  
  delegate :room_number,
    :to => :current_residentship,
    :allow_nil => true,
    :allow_override => true
end

I can then use a room_number field in the creation form, and an after_create method to create the residentship with the supplied room number.

Reported by Daniel Schierbeck · January 9th, 2009 @ 06:14 PM

State: wontfix
Milestone: 2.x
Assigned to: Pratik Pratik
Importance: none

Activity

  1. Pratik
    Pratik
    • Assigned user set to Pratik
    • State changed from new to wontfix

    Not sure I like the idea of making delegate API more complex. Also, using @method_name ivar looks like a hardcoded convention. Stuff like this shouldn't really be using delegate()

    Thanks!

    March 8th, 2009 @ 01:43 PM