adding initial support for belongs_to associations

This commit is contained in:
Sam Lown 2010-06-17 02:39:09 +02:00
parent 64e34ee2e8
commit a7a6b2f0ac
6 changed files with 143 additions and 2 deletions

View file

@ -19,6 +19,7 @@ module CouchRest
include CouchRest::Mixins::Collection
include CouchRest::Mixins::AttributeProtection
include CouchRest::Mixins::Attributes
include CouchRest::Mixins::Associations
# Including validation here does not work due to the way inheritance is handled.
#include CouchRest::Validation

View file

@ -10,3 +10,4 @@ require File.join(mixins_dir, 'class_proxy')
require File.join(mixins_dir, 'collection')
require File.join(mixins_dir, 'attribute_protection')
require File.join(mixins_dir, 'attributes')
require File.join(mixins_dir, 'associations')

View file

@ -0,0 +1,58 @@
module CouchRest
module Mixins
module Associations
# Basic support for relationships between ExtendedDocuments
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def belongs_to(attrib, *options)
opts = {
:foreign_key => attrib.to_s + '_id',
:class_name => attrib.to_s.camelcase
}
case options.first
when Hash
opts.merge!(options.first)
end
begin
opts[:class] = opts[:class_name].constantize
rescue
raise "Unable to convert belongs_to class name into Constant for #{self.name}##{attrib}"
end
prop = property(opts[:foreign_key])
create_belongs_to_getter(attrib, prop, opts)
create_belongs_to_setter(attrib, prop, opts)
prop
end
def create_belongs_to_getter(attrib, property, options)
class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{attrib}
@#{attrib} ||= #{options[:class_name]}.get(self.#{options[:foreign_key]})
end
EOS
end
def create_belongs_to_setter(attrib, property, options)
class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{attrib}=(value)
@#{attrib} = value
self.#{options[:foreign_key]} = value.nil? ? nil : value.id
end
EOS
end
end
end
end
end