Permalink
Browse files

Friendlier runtime exception if delegatee is nil

  • Loading branch information...
1 parent 50fe928 commit 63cc6b7242993a5c4d96df4479a4ad769f911576 @jeremy jeremy committed Jun 19, 2009
@@ -108,15 +108,21 @@ def delegate(*methods)
prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_"
- allow_nil = options[:allow_nil] && "#{to} && "
-
file, line = caller.first.split(':', 2)
line = line.to_i
methods.each do |method|
+ on_nil =
+ if options[:allow_nil]
+ 'return'
+ else
+ %(raise "#{self}##{prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
+ end
+
module_eval(<<-EOS, file, line)
def #{prefix}#{method}(*args, &block) # def customer_name(*args, &block)
- #{allow_nil}#{to}.__send__(#{method.inspect}, *args, &block) # client && client.__send__(:name, *args, &block)
+ #{on_nil} if #{to}.nil?
+ #{to}.__send__(#{method.inspect}, *args, &block) # client && client.__send__(:name, *args, &block)
end # end
EOS
end
@@ -142,7 +142,7 @@ def test_delegation_with_allow_nil_and_nil_value_and_prefix
def test_delegation_without_allow_nil_and_nil_value
david = Someone.new("David")
- assert_raise(NoMethodError) { david.street }
+ assert_raise(RuntimeError) { david.street }
end
def test_parent

0 comments on commit 63cc6b7

Please sign in to comment.