Class: ObjectAttorney::AssociationReflection

Inherits:
Reflection
  • Object
show all
Defined in:
lib/object_attorney/association_reflection.rb

Instance Attribute Summary collapse

Attributes inherited from Reflection

#klass, #name, #options

Instance Method Summary collapse

Methods inherited from Reflection

#plural_name, #single_name

Constructor Details

#initialize(association, related_reflection, options) ⇒ AssociationReflection

Returns a new instance of AssociationReflection.



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

def initialize(association, related_reflection, options)
  super(association, options)
  @macro = options[:macro] || macro_default(association)
  @related_reflection = related_reflection
end

Instance Attribute Details

#macroObject (readonly)

Returns the value of attribute macro.



4
5
6
# File 'lib/object_attorney/association_reflection.rb', line 4

def macro
  @macro
end

Returns the value of attribute related_reflection.



4
5
6
# File 'lib/object_attorney/association_reflection.rb', line 4

def related_reflection
  @related_reflection
end

Instance Method Details

#belongs_to?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/object_attorney/association_reflection.rb', line 52

def belongs_to?
  macro == :belongs_to
end

#foreign_keyObject



16
17
18
# File 'lib/object_attorney/association_reflection.rb', line 16

def foreign_key
  @foreign_key ||= options[:foreign_key] || foreign_key_default
end

#has_many?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/object_attorney/association_reflection.rb', line 44

def has_many?
  macro == :has_many
end

#has_one?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/object_attorney/association_reflection.rb', line 48

def has_one?
  macro == :has_one
end

#primary_keyObject



12
13
14
# File 'lib/object_attorney/association_reflection.rb', line 12

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

#primary_key_of(object) ⇒ Object



40
41
42
# File 'lib/object_attorney/association_reflection.rb', line 40

def primary_key_of(object)
  object.send(primary_key)
end

#set_foreign_key(object, id) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/object_attorney/association_reflection.rb', line 30

def set_foreign_key(object, id)
  setter = "#{foreign_key}="
  
  if object.respond_to?(setter)
    object.send(setter, id)
  elsif object.respond_to?("send_to_representative")
    object.send_to_representative(setter, id)
  end
end

#set_relational_keys(origin, destination) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/object_attorney/association_reflection.rb', line 20

def set_relational_keys(origin, destination)
  return nil if options[:standalone] == true
  
  if has_many? || has_one?
    set_foreign_key(destination, primary_key_of(origin))
  elsif belongs_to?
    set_foreign_key(origin, primary_key_of(destination))
  end
end