Module: ActiveRecord::VirtualAttributes::VirtualDelegates::ClassMethods

Defined in:
lib/active_record/virtual_attributes/virtual_delegates.rb

Instance Method Summary collapse

Instance Method Details

#virtual_delegate(*methods) ⇒ Object

Definition



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/active_record/virtual_attributes/virtual_delegates.rb', line 22

def virtual_delegate(*methods)
  options = methods.extract_options!
  unless (to = options[:to])
    raise ArgumentError, 'Delegation needs an association. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).'
  end

  to = to.to_s
  if to.include?(".") && methods.size > 1
    raise ArgumentError, 'Delegation only supports specifying a method name when defining a single virtual method'
  end

  if to.count(".") > 1
    raise ArgumentError, 'Delegation needs a single association. Supply an option hash with a :to key with only 1 period (e.g. delegate :hello, to: "greeter.greeting")'
  end

  allow_nil = options[:allow_nil]
  default = options[:default]

  # put method entry per method name.
  # This better supports reloading of the class and changing the definitions
  methods.each do |method|
    method_prefix = virtual_delegate_name_prefix(options[:prefix], to)
    method_name = "#{method_prefix}#{method}"
    if to.include?(".") # to => "target.method"
      to, method = to.split(".").map(&:to_sym)
      options[:to] = to
    end

    define_delegate(method_name, method, :to => to, :allow_nil => allow_nil, :default => default)

    self.virtual_delegates_to_define =
      virtual_delegates_to_define.merge(method_name => [method, options])
  end
end