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, to:, type:, prefix: nil, allow_nil: nil, default: nil, uses: nil, **options) ⇒ Object

Definition



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/active_record/virtual_attributes/virtual_delegates.rb', line 17

def virtual_delegate(*methods, to:, type:, prefix: nil, allow_nil: nil, default: nil, uses: nil, **options) # rubocop:disable Naming/MethodParameterName
  to = to.to_s
  if to.include?(".") && (methods.size > 1 || prefix)
    raise ArgumentError, 'Delegation only supports specifying a target method name when defining a single virtual method with no prefix'
  end

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

  # put method entry per method name.
  # This better supports reloading of the class and changing the definitions
  methods.each do |method|
    method_name, to, method = determine_method_names(method, to, prefix)
    unless (to_ref = reflection_with_virtual(to))
      raise ArgumentError, "Delegation needs an association. Association #{to} does not exist"
    end

    define_delegate(method_name, method, :to => to, :allow_nil => allow_nil, :default => default)
    virtual_attribute(method_name, type, :uses => (uses || to), :arel => virtual_delegate_arel(method, to_ref), **options)
  end
end