Module: ActiveRecord::Associations::CollectionProxy::InterceptDynamicInstantiators

Defined in:
lib/active_record/deprecated_finders/collection_proxy.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/active_record/deprecated_finders/collection_proxy.rb', line 5

def method_missing(method, *args, &block)
  match = DynamicMatchers::Method.match(klass, method)

  if match && match.is_a?(DynamicMatchers::Instantiator)
    scoping do
      klass.send(method, *args) do |record|

        sanitized_method = match.class.prefix + match.class.suffix
        if %w(find_or_create_by find_or_create_by!).include?(sanitized_method) && proxy_association.reflection.options[:through].present?
          proxy_association.send(:save_through_record, record)
        else
          proxy_association.add_to_target(record)
        end
        yield record if block_given?
      end
    end
  else
    super
  end
end