Class: AdvancedAR::ArbitraryPrefetch::PrefetcherContext

Inherits:
Object
  • Object
show all
Defined in:
lib/advanced_ar/arbitrary_prefetch.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, opts) ⇒ PrefetcherContext

Returns a new instance of PrefetcherContext.



22
23
24
25
26
27
28
29
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 22

def initialize(model, opts)
  @options = opts
  @model = model
  @source_key = opts[:relation]
  @target_attribute = opts[:attribute]
  @queryset = opts[:queryset]
  @models = []
end

Instance Attribute Details

#modelObject

Returns the value of attribute model.



19
20
21
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 19

def model
  @model
end

#optionsObject (readonly)

Returns the value of attribute options.



20
21
22
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 20

def options
  @options
end

#target_attributeObject

Returns the value of attribute target_attribute.



19
20
21
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 19

def target_attribute
  @target_attribute
end

Instance Method Details



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 31

def link_models(models)
  Array(models).each do |m|
    @models << m

    # assoc = PrefetchAssociation.new(m, self, reflection)
    assoc = reflection.association_class.new(m, reflection)
    m.send(:association_instance_set, target_attribute, assoc)

    m.instance_eval <<-CODE, __FILE__, __LINE__ + 1
      def #{target_attribute}
        association(:#{target_attribute}).reader
      end
    CODE
  end
end

#reflectionObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/advanced_ar/arbitrary_prefetch.rb', line 47

def reflection
  @reflection ||= begin
    queryset = @queryset
    source_refl = model.reflections[@source_key.to_s]
    scope = lambda { |*_args|
      qs = queryset
      qs = qs.merge(source_refl.scope_for(model.unscoped)) if source_refl.scope
      qs
    }
    ActiveRecord::Reflection.create(
      options[:type],
      @target_attribute,
      scope,
      source_refl.options.merge(
        class_name: source_refl.class_name,
        inverse_of: nil
      ),
      model
    )
  end
end