diff options
Diffstat (limited to 'activesupport/lib/active_support/core_ext/module/delegation.rb')
-rw-r--r-- | activesupport/lib/active_support/core_ext/module/delegation.rb | 28 |
1 files changed, 27 insertions, 1 deletions
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb index 2905eebc85..5c75bd4938 100644 --- a/activesupport/lib/active_support/core_ext/module/delegation.rb +++ b/activesupport/lib/active_support/core_ext/module/delegation.rb @@ -72,6 +72,30 @@ class Module # invoice.customer_name # => "John Doe" # invoice.customer_address # => "Vimmersvej 13" # + # If the object to which you delegate can be nil, you may want to use the + # :allow_nil option. In that case, it returns nil instead of raising a + # NoMethodError exception: + # + # class Foo + # attr_accessor :bar + # def initialize(bar = nil) + # @bar = bar + # end + # delegate :zoo, :to => :bar + # end + # + # Foo.new.zoo # raises NoMethodError exception (you called nil.zoo) + # + # class Foo + # attr_accessor :bar + # def initialize(bar = nil) + # @bar = bar + # end + # delegate :zoo, :to => :bar, :allow_nil => true + # end + # + # Foo.new.zoo # returns nil + # def delegate(*methods) options = methods.pop unless options.is_a?(Hash) && to = options[:to] @@ -84,10 +108,12 @@ class Module prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_" + allow_nil = options[:allow_nil] && "#{to} && " + methods.each do |method| module_eval(<<-EOS, "(__DELEGATION__)", 1) def #{prefix}#{method}(*args, &block) - #{to}.__send__(#{method.inspect}, *args, &block) + #{allow_nil}#{to}.__send__(#{method.inspect}, *args, &block) end EOS end |