Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #4134: delegate_to_nil.patch

File delegate_to_nil.patch, 1.2 kB (added by zapnap, 2 years ago)

return nil if delegation target is nil instead of blowing up with a NoMethodError

  • activesupport/test/core_ext/module_test.rb

    old new  
    8080    assert_equal "DAVID HANSSON", david.upcase 
    8181  end 
    8282 
     83  def test_delegation_to_nil 
     84    david = Someone.new("David", nil) 
     85    assert_equal nil, david.city 
     86  end 
     87 
    8388  def test_missing_delegation_target 
    8489    assert_raises(ArgumentError) { eval($nowhere) } 
    8590    assert_raises(ArgumentError) { eval($noplace) } 
  • activesupport/lib/active_support/core_ext/module/delegation.rb

    old new  
    3333    methods.each do |method| 
    3434      module_eval(<<-EOS, "(__DELEGATION__)", 1) 
    3535        def #{method}(*args, &block) 
    36           #{to}.__send__(#{method.inspect}, *args, &block) 
     36          #{to}.__send__("nil?") ? nil : #{to}.__send__(#{method.inspect}, *args, &block) 
    3737        end 
    3838      EOS 
    3939    end