This project is archived and is in readonly mode.

#1720 ✓wontfix
Daniel Schierbeck

Allow overriding a delegation

Reported by Daniel Schierbeck | January 9th, 2009 @ 06:14 PM | in 2.x

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.

Comments and changes to this ticket

  • Pratik

    Pratik March 8th, 2009 @ 01:43 PM

    • 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!

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Attachments

Pages