lib/pickle_dupe/adapter.rb in pickle-dupe-0.2.0 vs lib/pickle_dupe/adapter.rb in pickle-dupe-0.2.1
- old
+ new
@@ -15,16 +15,21 @@
def self.factories
(::Dupe.models.values rescue []).map {|model| new(model)}
end
def initialize(model)
- @klass, @name = model.name.to_s.classify.constantize, model.name.to_s
+ # Not all dupe models has an associated model class
+ # so we dynamically create them here
+ unless @klass = (model.name.to_s.classify.constantize rescue nil)
+ Object.const_set(model.name.to_s.classify, Class.new(ActiveResource::Base))
+ end
+ @name = model.name.to_s
end
def create(attrs = {})
duped_object = ::Dupe.create(@name, attrs)
- assign_missing_associations(duped_object, attrs) unless attrs.blank?
+ assign_missing_associations (duped_object, attrs) unless attrs.blank?
return duped_object
end
private
@@ -72,25 +77,17 @@
# Dupe.create :recipe, {:ingredients => [<Duped::Ingredient>,<Duped::Ingredient>]}
#
def assign_missing_associations(duped_object, attrs)
association_objects = collect_association_objects(attrs)
association_objects.each {|association_object|
-
# When a pickle step causes Dupe to do the following:
#
# Dupe.create(:direction_step, :recipe => @recipe)
#
# Then duped_object would be of class Dupe::DirectionStep and association_object would be of
# class Dupe::Recipe.
- #
- if association_object.kind_of?(Array)
- association_object.each {|a|
- assign_association(a, duped_object)
- }
- else
- assign_association(association_object, duped_object)
- end
+ assign_association(association_object, duped_object)
}
end
def assign_association(association_object, duped_object)
has_one_association = duped_object.__model__.name #=> :direction_step
@@ -110,10 +107,10 @@
# Given :association => <#Duped::Ingredient name="ingredient 1 name" recipes=[] label="ingredient-1-name" id=1> or
# :association => [<#Duped...>] will return [[<#Duped...>,<#Duped...>],<#Duped...>]
def collect_association_objects(attrs)
attrs.select {|k,v|
v.kind_of?(Array) || v.kind_of?(::Dupe::Database::Record)
- }.collect {|i| i[1]}
+ }.collect {|i| i[1]}.flatten
end
end
end
\ No newline at end of file