Module: ForeignModel::ClassMethods

Defined in:
lib/foreign_model.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to_foreign_model(name, options = {}) ⇒ Object



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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/foreign_model.rb', line 14

def belongs_to_foreign_model(name, options={})
  options[:class_name] ||= ForeignModel.camelize(name)
  
  ForeignModel::SCOPE_PROCS[self][name] = begin
    if options[:scope]
      options[:scope]
    elsif options[:polymorphic]
      proc do |r|
        type = r.send("#{name}_type")
        type and eval(type)
      end
    else
      #TODO: this is a hack
      proc{ eval(options[:class_name]) }
    end
  end
  
  define_method :_foreign_models do
    @_foreign_models ||= {}
  end
  
  define_method :_parent_procs do
    @_parent_procs ||= {}
  end
   
  define_method :parent_proc_for do |foreign_model_name|
    _parent_procs[foreign_model_name] ||= ForeignModel::SCOPE_PROCS[self.class][foreign_model_name].call(self)
  end
  
  define_method name do
    if parent_proc_for(name) && send("#{name}_id") && send("#{name}_id") != ""
      _foreign_models[name] ||= parent_proc_for(name).find(send("#{name}_id"))
    end
  end
  
  define_method "#{name}=" do |foreign_model|
    _foreign_models[name] = foreign_model
    if foreign_model
      send("#{name}_id=",   foreign_model.id)
      send("#{name}_type=", foreign_model.class.name) if respond_to? "#{name}_type="
    end
  end
  
  define_method "#{name}_id=" do |foreign_model_id|
    if send("#{name}_id") != foreign_model_id
      write_raw_attribute("#{name}_id", foreign_model_id)
      _foreign_models[name] = nil
    end
  end
  
  if options[:polymorphic]
    define_method "#{name}_type=" do |foreign_model_type|
      if send("#{name}_type") != foreign_model_type
        write_raw_attribute("#{name}_type", foreign_model_type)
        _foreign_models[name] = nil
      end
    end
  end
end