Module: LogicalModel::Associations::BelongsTo::ClassMethods

Defined in:
lib/logical_model/associations/belongs_to.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(key, options = {}) ⇒ Object

Parameters:

  • key (String)

    association name

  • options (Hash) (defaults to: {})

Options Hash (options):

  • class (String/Constant)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/logical_model/associations/belongs_to.rb', line 13

def belongs_to(key, options = {})
  attr_accessor "#{key}_id"
  attr_class = get_attr_class(key, options)

  @belongs_to_keys ||= {}
  @belongs_to_keys.merge!({key => attr_class})

  define_method("#{key}=") do |param|
    if param.is_a?(Hash)
      param.stringify_keys!
      instance_variable_set("@#{key}_id", param['id']) if param['id']
      instance = attr_class.new(param)
    elsif param.is_a?(attr_class)
      instance_variable_set("@#{key}_id", param.id)
      instance = param
    else
      # ...
    end

    instance_variable_set("@#{key}",instance)
  end

  define_method(key) do
    instance = eval("@#{key}")
    if instance.nil?
      instance = attr_class.find(eval("#{key}_id"))
      instance_variable_set("@#{key}",instance)
    end
    instance
  end

  # TODO define_method("#{key}_attribute="){|param| ... }

  define_method "new_#{key}" do |param|
    attr_class

    return unless attr_class

    temp_object = attr_class.new(param.merge({"#{self.json_root}_id" => self.id}))
    eval(key.to_s) << temp_object
    temp_object
  end
end

#belongs_to_keysObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/logical_model/associations/belongs_to.rb', line 57

def belongs_to_keys
  # This hack was needed to consider the case where the belongs_to was set on a parent class, for example:
  #
  # class ContactAttribute < LogicalModel
  #   ...
  #   belongs_to :contact
  # end
  #
  # class Telephone < ContactAttribute
  #   ...
  # end
  #
  # It returns the parent's class variable if present.  
  result = nil
  if !@belongs_to_keys.nil?
    result = @belongs_to_keys
  elsif self.superclass.respond_to? :belongs_to_keys
    result = self.superclass.belongs_to_keys
  else
    result = nil
  end
  result
end