Module: LogicalModel::BelongsTo::ClassMethods

Defined in:
lib/logical_model/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)


12
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
# File 'lib/logical_model/belongs_to.rb', line 12

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

  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