Class: Module

Inherits:
Object
  • Object
show all
Defined in:
lib/inquisitor/extensions.rb

Overview

Module.delegate by active_support

Instance Method Summary collapse

Instance Method Details

#delegate(*methods) ⇒ Object

File activesupport/lib/active_support/core_ext/module/delegation.rb, line 106



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/inquisitor/extensions.rb', line 4

def delegate(*methods)
  options = methods.pop
  unless options.is_a?(Hash) && to = options[:to]
    raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
  end

  if options[:prefix] == true && options[:to].to_s =~ /^[^a-z_]/
    raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
  end

  prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_" || ''

  file, line = caller.first.split(':', 2)
  line = line.to_i

  methods.each do |method|
    on_nil =
      if options[:allow_nil]
        'return'
      else
        %Q(raise "#{self}##{prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
      end

    module_eval("        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}                                       #     return # depends on :allow_nil
        else                                              #   else
          raise                                           #     raise
        end                                               #   end
      end                                                 # end
", file, line - 1)
  end
end