Class: SimpleMaster::Master::Association::HasManyThroughAssociation

Inherits:
SimpleMaster::Master::Association show all
Defined in:
lib/simple_master/master/association/has_many_through_association.rb

Instance Attribute Summary

Attributes inherited from SimpleMaster::Master::Association

#defined_at, #name, #options

Instance Method Summary collapse

Methods inherited from SimpleMaster::Master::Association

#initialize, #is_active_record?, #target_class

Constructor Details

This class inherits a constructor from SimpleMaster::Master::Association

Instance Method Details

#foreign_keyObject



7
8
9
# File 'lib/simple_master/master/association/has_many_through_association.rb', line 7

def foreign_key
  @foreign_key ||= (options[:foreign_key] || ActiveSupport::Inflector.foreign_key(defined_at.to_s)).to_sym
end

#init(master_class) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/simple_master/master/association/has_many_through_association.rb', line 38

def init(master_class)
  # check
  through_association

  master_class.simple_master_module.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    def #{name}
      Array.wrap(#{through}).flat_map { |ass| ass.#{source} }.compact
    end
  RUBY
end

#init_for_test(master_class) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/simple_master/master/association/has_many_through_association.rb', line 49

def init_for_test(master_class)
  master_class.simple_master_module.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    def #{name}=(values)
      self.#{through} = values.map { |value|
        #{through_association.target_class}.new.tap do |through|
          through.#{source} = value
          #{"through.#{through_association.inverse_of} = self" if through_association.try(:inverse_of)}
        end
      }
    end
  RUBY
end

#primary_keyObject



34
35
36
# File 'lib/simple_master/master/association/has_many_through_association.rb', line 34

def primary_key
  @primary_key ||= options[:primary_key] || :id
end

#sourceObject



30
31
32
# File 'lib/simple_master/master/association/has_many_through_association.rb', line 30

def source
  @source ||= options[:source] || ActiveSupport::Inflector.singularize(name)
end

#throughObject



11
12
13
# File 'lib/simple_master/master/association/has_many_through_association.rb', line 11

def through
  @through ||= options[:through]
end

#through_associationObject



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/simple_master/master/association/has_many_through_association.rb', line 15

def through_association
  @through_association ||=
    begin
      through_association = defined_at.all_has_many_associations.find { |ass| ass.name == through }

      if through_association.nil?
        fail "Association '#{through}' not found in has_many_associations. Use 'delegate' instead."
      end

      through_association
    end
end