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.