lib/active_remote/association.rb in active_remote-1.2.1 vs lib/active_remote/association.rb in active_remote-1.3.0

- old
+ new

@@ -35,24 +35,13 @@ # def client # Client.search(:guid => self.client_guid).first # end # end # - def belongs_to(*klass_names) - klass_names.flatten.compact.uniq.each do |klass_name| - - define_method(klass_name) do - value = instance_variable_get(:"@#{klass_name}") - - unless value - klass = klass_name.to_s.classify.constantize - value = klass.search(:guid => read_attribute(:"#{klass_name}_guid")).first - instance_variable_set(:"@#{klass_name}", value) - end - - return value - end + def belongs_to(belongs_to_klass, options={}) + perform_association( belongs_to_klass, options ) do |klass, obj| + klass.search(:guid => obj.read_attribute(:"#{belongs_to_klass}_guid")).first end end # Create a `has_many` association for a given remote resource. # Specify one or more associations to define. The constantized @@ -82,25 +71,13 @@ # def users # User.search(:client_guid => self.guid) # end # end # - def has_many(*klass_names) - klass_names.flatten.compact.uniq.each do |plural_klass_name| - singular_name = plural_klass_name.to_s.singularize - - define_method(plural_klass_name) do - values = instance_variable_get(:"@#{plural_klass_name}") - - unless values - klass = plural_klass_name.to_s.classify.constantize - values = klass.search(:"#{self.class.name.demodulize.underscore}_guid" => self.guid) - instance_variable_set(:"@#{plural_klass_name}", values) - end - - return values - end + def has_many(has_many_class, options={}) + perform_association( has_many_class, options ) do |klass, obj| + klass.search(:"#{obj.class.name.demodulize.underscore}_guid" => obj.guid) end end # Create a `has_one` association for a given remote resource. # Specify one or more associations to define. The constantized @@ -129,23 +106,29 @@ # def client # Client.search(:user_guid => self.guid).first # end # end # - def has_one(*klass_names) - klass_names.flatten.compact.uniq.each do |klass_name| + def has_one(has_one_klass, options={}) + perform_association( has_one_klass, options ) do |klass, obj| + klass.search(:"#{obj.class.name.demodulize.underscore}_guid" => obj.guid).first + end + end - define_method(klass_name) do - value = instance_variable_get(:"@#{klass_name}") + private - unless value - klass = klass_name.to_s.classify.constantize - value = klass.search(:"#{self.class.name.demodulize.underscore}_guid" => self.guid).first - instance_variable_set(:"@#{klass_name}", value) - end + def perform_association(associated_klass, optionz={}) + define_method(associated_klass) do + value = instance_variable_get(:"@#{associated_klass}") - return value + unless value + klass_name = optionz.fetch(:class_name){ associated_klass } + klass = klass_name.to_s.classify.constantize + value = yield( klass, self ) + instance_variable_set(:"@#{associated_klass}", value) end + + return value end end end end end