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
39
# 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
  src_loc = caller_locations
  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)

    # NOTE: delete_blank will remove a default of []. we only want to remove nils
    va_params = options.merge(:uses => uses, :through => to, :source => method, :default => default).delete_if { |_n, v| v.nil? }

    ActiveRecord::VirtualAttributes.deprecator.warn("virtual_delegate is deprecated in favor of virtual_attribute. Change to: #{name}.virtual_attribute #{method_name.inspect}, #{type.inspect}, #{va_params.map { |k, v| "#{k.inspect} => #{v.inspect}" }.join(", ")}", src_loc)
    virtual_attribute(method_name, type, **va_params)
  end
end