Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/active_support/core_ext/module/better_delegation.rb

Class Method Summary collapse

Class Method Details

.delegate(*methods) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/active_support/core_ext/module/better_delegation.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]}_"

  methods.each do |method|
    define_method method do
      send(:delegator_for, to).send(method)
    end
    define_method "#{method}=" do |value|
      send(:delegator_for, to).send("#{method}=", value)
    end
  end
end