Module: FerryCore::ModuleExtensions

Defined in:
lib/locomotive/core_extensions/module.rb

Overview

extensions to enhance an object with some attributes and derive simple methods

Instance Method Summary collapse

Instance Method Details

#attributes(*attrs) ⇒ Object

extend the instance with some new attributes



26
27
28
29
# File 'lib/locomotive/core_extensions/module.rb', line 26

def attributes(*attrs)
  @attributes = attrs
  attr_reader(*attrs)
end

#delegate(*methods) ⇒ Object

stolen from active_support reimplement it by time since it use deprecated string metaprogramming



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/locomotive/core_extensions/module.rb', line 37

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
        %(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)
        #{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

#deriving(*methods) ⇒ Object



31
32
33
# File 'lib/locomotive/core_extensions/module.rb', line 31

def deriving(*methods)
  methods.each(&method(:derive))
end