Class: Bigamy::BelongsTo

Inherits:
Proxy
  • Object
show all
Defined in:
lib/bigamy/proxy.rb

Direct Known Subclasses

ARBelongsTo, MongoBelongsTo

Instance Attribute Summary

Attributes inherited from Proxy

#klass, #me, #methods_added, #name, #options, #primary_key

Instance Method Summary collapse

Methods inherited from Proxy

#create_accessors, #divorce_everyone, #root_klass, #root_klass_name, #serialize_foreign_key, #target_klass, #target_klass_name

Constructor Details

#initialize(parent, name, options) ⇒ BelongsTo

Returns a new instance of BelongsTo.



123
124
125
# File 'lib/bigamy/proxy.rb', line 123

def initialize parent, name, options
  super
end

Instance Method Details

#add_getterObject



131
132
133
134
135
136
137
138
139
# File 'lib/bigamy/proxy.rb', line 131

def add_getter
  code = <<-EOF
    def #{name}
      self.id.blank? ? nil : #{klass}.first(:conditions => {:#{primary_key} => export_id_val(self.id)})
    end
  EOF

  me.class_eval code, __FILE__, __LINE__
end

#add_setterObject



141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/bigamy/proxy.rb', line 141

def add_setter
  code = <<-EOF
    def #{name}= val
      raise NewRecordAssignment if val.new_record?
      raise TypeError.new("Should get #{klass}") unless val.is_a? #{klass}

      set_value :#{foreign_key}, val.id
    end
  EOF

  me.class_eval code, __FILE__, __LINE__ 
end

#foreign_keyObject



127
128
129
# File 'lib/bigamy/proxy.rb', line 127

def foreign_key
  options[:foreign_key] || :"#{target_klass_name}_id"
end