Class: EagerLoadablePolymorphicAssociation::AssociationWriter

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

Instance Method Summary collapse

Constructor Details

#initialize(association, types) ⇒ AssociationWriter

Returns a new instance of AssociationWriter.

Raises:

  • (ArgumentError)


6
7
8
9
10
# File 'lib/eager_loadable_polymorphic_association.rb', line 6

def initialize(association, types)
  raise ArgumentError, "#{association} is not polymorphic association" unless association.options[:polymorphic]
  @association = association
  @types = types
end

Instance Method Details

#belong_to_them(ref_from) ⇒ Object



12
13
14
15
16
# File 'lib/eager_loadable_polymorphic_association.rb', line 12

def belong_to_them(ref_from)
  @types.each do |t|
    ref_from.belongs_to t, readonly: true, foreign_key: fk, conditions: condition_sql(t.to_s.classify.constantize)
  end
end

#define_scope(ref_from) ⇒ Object



18
19
20
# File 'lib/eager_loadable_polymorphic_association.rb', line 18

def define_scope(ref_from)
  ref_from.scope "with_#{@association.name}", ref_from.includes(*@types)
end

#override_accessor(ref_from) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/eager_loadable_polymorphic_association.rb', line 22

def override_accessor(ref_from)
  ref_from.class_eval "    def \#{@association.name}\n      concreate_item = association(self[\#{ft.dump}].underscore.to_sym)\n      polymorphic_item = association(:\#{@association.name})\n      if concreate_item.loaded? && !polymorphic_item.loaded?\n        polymorphic_item.target = concreate_item.target\n      end\n      super\n    end\n  RUBY\nend\n".strip_heredoc