Class: PluckMap::Relationships::PolymorphicOne

Inherits:
Attribute
  • Object
show all
Defined in:
lib/pluck_map/relationships/polymorphic_one.rb

Instance Attribute Summary

Attributes inherited from Attribute

#block, #id, #indexes, #model, #name, #selects, #value

Instance Method Summary collapse

Methods inherited from Attribute

#==, #apply, #eql?, #exec, #hash, #to_ruby, #value?, #values, #will_map?

Constructor Details

#initialize(attribute_name, reflection, block, options) ⇒ PolymorphicOne

Returns a new instance of PolymorphicOne.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/pluck_map/relationships/polymorphic_one.rb', line 7

def initialize(attribute_name, reflection, block, options)
  @reflection = reflection
  @attributes_block = block
  @scope_block = options[:scope_block]

  options = options.slice(:as).merge(
    select: [ reflection.foreign_type.to_sym, reflection.foreign_key.to_sym ],
    map: ->(*args) { @preloads[args] })

  super(attribute_name, reflection.active_record, options)
end

Instance Method Details

#nested?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/pluck_map/relationships/polymorphic_one.rb', line 19

def nested?
  true
end

#preload!(results) ⇒ Object



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
# File 'lib/pluck_map/relationships/polymorphic_one.rb', line 23

def preload!(results)
  ids_by_type = Hash.new { |hash, key| hash[key] = [] }

  results.each do |values|
    type, id = values.values_at(*indexes)
    ids_by_type[type].push(id)
  end

  @preloads = Hash.new
  ids_by_type.each do |type, ids|
    klass = type.constantize
    scope = klass.where(id: ids)
    scope = scope.instance_exec(&@scope_block) if @scope_block

    presenter = PluckMap[klass].define do |q|
      q.__id select: klass.primary_key.to_sym

      if @attributes_block.arity == 1
        @attributes_block.call(q)
      else
        q.instance_eval(&@attributes_block)
      end
    end

    presenter.to_h(scope).each do |h|
      id = h.delete(:__id)
      @preloads[[type, id]] = h
    end
  end

  nil
end