lib/motion-resource/associations.rb in motion-resource-0.1.2 vs lib/motion-resource/associations.rb in motion-resource-0.1.3

- old
+ new

@@ -15,11 +15,17 @@ define_method "reset_#{name}" do instance_variable_set("@#{name}", nil) end end - def has_many(name, params = lambda { |o| Hash.new }) + def has_many(name, options = {}) + default_options = { + :params => lambda { |o| Hash.new }, + :class_name => name.to_s.classify + } + options = default_options.merge(options) + backwards_association = self.name.underscore define_method name do |&block| if block.nil? instance_variable_get("@#{name}") || [] @@ -27,12 +33,14 @@ if cached = instance_variable_get("@#{name}") cached_response = instance_variable_get("@#{name}_response") MotionResource::Base.request_block_call(block, cached, cached_response) return end + + klass = options[:class_name].constantize - Object.const_get(name.to_s.classify).find_all(params.call(self)) do |results, response| + klass.find_all(options[:params].call(self)) do |results, response| if results && results.first && results.first.respond_to?("#{backwards_association}=") results.each do |result| result.send("#{backwards_association}=", self) end end @@ -42,10 +50,11 @@ end end end define_method "#{name}=" do |array| - klass = Object.const_get(name.to_s.classify) + klass = options[:class_name].constantize + instance_variable_set("@#{name}", []) array.each do |value| value = klass.instantiate(value) if value.is_a?(Hash) instance_variable_get("@#{name}") << value