Class: SimpleMaster::Master::Association::BelongsToAssociation

Inherits:
SimpleMaster::Master::Association show all
Defined in:
lib/simple_master/master/association/belongs_to_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/belongs_to_association.rb', line 7

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

#init(master_class) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/simple_master/master/association/belongs_to_association.rb', line 15

def init(master_class)
  master_class.simple_master_module.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    if #{target_class} < SimpleMaster::Master
      def #{name}
        return nil unless #{foreign_key}

        #{search_code}
      end
    else
      def #{name}
        return nil unless #{foreign_key}

        belongs_to_store[:#{name}] ||= #{target_class}.simple_master_connection.find_by_#{primary_key}(#{foreign_key})
      end
    end
  RUBY
end

#init_for_test(master_class) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/simple_master/master/association/belongs_to_association.rb', line 33

def init_for_test(master_class)
  master_class.simple_master_module.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    if #{target_class} < SimpleMaster::Master
      def #{name}
        return belongs_to_store[:#{name}] if belongs_to_store[:#{name}]
        return nil unless #{foreign_key}

        #{search_code}
      end
    else
      def #{name}
        return nil unless #{foreign_key}

        belongs_to_store[:#{name}] ||= #{target_class}.simple_master_connection.find_by_#{primary_key}(#{foreign_key})
      end
    end

    def #{name}=(value)
      @_association_#{name}_source = self.#{foreign_key} = value&.#{primary_key}
      belongs_to_store[:#{name}] = value
    end

    def _#{name}_target_save?
      # Skip saving the association if the key changed after assignment
      return false if @_association_#{name}_source != #{foreign_key}

      target = belongs_to_store[:#{name}]
      return false if target.nil?

      true
    end
  RUBY
end

#primary_keyObject



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

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