Class: SimpleMaster::Master::Association::HasOneAssociation

Inherits:
SimpleMaster::Master::Association show all
Defined in:
lib/simple_master/master/association/has_one_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_one_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



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/simple_master/master/association/has_one_association.rb', line 19

def init(master_class)
  master_class.simple_master_module.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    if #{target_class} < SimpleMaster::Master
      def #{name}
        #{target_class}.find_by(:#{foreign_key}, #{primary_key})
      end
    else
      def #{name}
        # Store in an Array so nil values still hit the cache
        values = (has_many_store[:#{name}] ||= [#{target_class}.simple_master_connection.find_by_#{foreign_key}(#{primary_key})])
        values.first
      end
    end
  RUBY
end

#init_for_test(master_class) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/simple_master/master/association/has_one_association.rb', line 35

def init_for_test(master_class)
  master_class.simple_master_module.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    if #{target_class} < SimpleMaster::Master
      def #{name}
        (has_many_store[:#{name}] || #{target_class}.all_by(:#{foreign_key}, #{primary_key})).first
      end
    else
      def #{name}
        # Store in an Array so nil values still hit the cache
        values = (has_many_store[:#{name}] ||= [#{target_class}.simple_master_connection.find_by_#{foreign_key}(#{primary_key})])
        values.first
      end
    end

    def #{name}=(value)
      has_many_store[:#{name}] = [value]
    end
  RUBY
end

#inverse_ofObject



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

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

#primary_keyObject



15
16
17
# File 'lib/simple_master/master/association/has_one_association.rb', line 15

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