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

#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.



139
140
141
# File 'lib/bigamy/proxy.rb', line 139

def initialize parent, name, options
  super
end

Instance Method Details

#add_getterObject



147
148
149
150
151
152
153
154
155
# File 'lib/bigamy/proxy.rb', line 147

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

  me.class_eval code, __FILE__, __LINE__
end

#add_setterObject



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/bigamy/proxy.rb', line 157

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

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

  me.class_eval code, __FILE__, __LINE__ 
end

#foreign_keyObject



143
144
145
# File 'lib/bigamy/proxy.rb', line 143

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