mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Allow delegating to nil, because the method might actually exist on it
This commit is contained in:
parent
d0f891ae02
commit
d15ddf04ec
2 changed files with 21 additions and 5 deletions
|
@ -120,10 +120,15 @@ class Module
|
|||
end
|
||||
|
||||
module_eval(<<-EOS, file, line)
|
||||
def #{prefix}#{method}(*args, &block) # def customer_name(*args, &block)
|
||||
#{on_nil} if #{to}.nil?
|
||||
#{to}.__send__(#{method.inspect}, *args, &block) # client && client.__send__(:name, *args, &block)
|
||||
end # end
|
||||
def #{prefix}#{method}(*args, &block) # def customer_name(*args, &block)
|
||||
#{to}.__send__(#{method.inspect}, *args, &block) # client.__send__(:name, *args, &block)
|
||||
rescue NoMethodError # rescue NoMethodError
|
||||
if #{to}.nil? # if client.nil?
|
||||
#{on_nil}
|
||||
else # else
|
||||
raise # raise
|
||||
end # end
|
||||
end # end
|
||||
EOS
|
||||
end
|
||||
end
|
||||
|
|
|
@ -32,7 +32,7 @@ end
|
|||
Somewhere = Struct.new(:street, :city)
|
||||
|
||||
Someone = Struct.new(:name, :place) do
|
||||
delegate :street, :city, :to => :place
|
||||
delegate :street, :city, :to_f, :to => :place
|
||||
delegate :state, :to => :@place
|
||||
delegate :upcase, :to => "place.city"
|
||||
end
|
||||
|
@ -44,6 +44,7 @@ end
|
|||
|
||||
Project = Struct.new(:description, :person) do
|
||||
delegate :name, :to => :person, :allow_nil => true
|
||||
delegate :to_f, :to => :description, :allow_nil => true
|
||||
end
|
||||
|
||||
class Name
|
||||
|
@ -145,6 +146,16 @@ class ModuleTest < Test::Unit::TestCase
|
|||
assert_raise(RuntimeError) { david.street }
|
||||
end
|
||||
|
||||
def test_delegation_to_method_that_exists_on_nil
|
||||
nil_person = Someone.new(nil)
|
||||
assert_equal 0.0, nil_person.to_f
|
||||
end
|
||||
|
||||
def test_delegation_to_method_that_exists_on_nil_when_allowing_nil
|
||||
nil_project = Project.new(nil)
|
||||
assert_equal 0.0, nil_project.to_f
|
||||
end
|
||||
|
||||
def test_parent
|
||||
assert_equal Yz::Zy, Yz::Zy::Cd.parent
|
||||
assert_equal Yz, Yz::Zy.parent
|
||||
|
|
Loading…
Reference in a new issue