lib/embedded_associations.rb in embedded_associations-0.0.2 vs lib/embedded_associations.rb in embedded_associations-0.0.3

- old
+ new

@@ -29,13 +29,11 @@ def root_resource_name resource_name end # Simple callbacks for now, eventually should use a filter system - def before_embedded_update(record); end - def before_embedded_create(record); end - def before_embedded_destroy(record); end + def before_embedded(record, action); end class Definitions include Enumerable attr_accessor :definitions @@ -100,10 +98,14 @@ handle_singular_resource parent, name, attrs, child_definition end end end + def filter_attributes(name, attrs, action) + attrs + end + def handle_plural_resource(parent, name, attr_array, child_definition) current_assoc = parent.send(name) # Mark non-existant records as deleted current_assoc.select{|r| attr_array.none?{|attrs| attrs['id'] && attrs['id'].to_i == r.id}}.each do |r| @@ -114,51 +116,56 @@ attr_array.each do |attrs| if id = attrs['id'] # can't use current_assoc.find(id), see http://stackoverflow.com/questions/11605120/autosave-ignored-on-has-many-relation-what-am-i-missing r = current_assoc.find{|r| r.id == id.to_i} + attrs = filter_attributes(r.class.name, attrs, :update) handle_resource(child_definition, r, attrs) if child_definition r.assign_attributes(attrs) run_before_update_callbacks(r) else r = current_assoc.build() + attrs = filter_attributes(r.class.name, attrs, :create) handle_resource(child_definition, r, attrs) if child_definition r.assign_attributes(attrs) run_before_create_callbacks(r) end end end def handle_singular_resource(parent, name, attrs, child_definition) current_assoc = parent.send(name) + if r = current_assoc if attrs + attrs = filter_attributes(r.class.name, attrs, :update) handle_resource(child_definition, r, attrs) if child_definition r.assign_attributes(attrs) run_before_update_callbacks(r) else handle_resource(child_definition, r, attrs) if child_definition run_before_destroy_callbacks(r) r.mark_for_destruction end elsif attrs r = parent.send("build_#{name}") + attrs = filter_attributes(r.class.name, attrs, :create) handle_resource(child_definition, r, attrs) if child_definition r.assign_attributes(attrs) run_before_create_callbacks(r) end end def run_before_create_callbacks(record) - controller.send(:before_embedded_create, record) + controller.send(:before_embedded, record, :create) end def run_before_update_callbacks(record) - controller.send(:before_embedded_update, record) + controller.send(:before_embedded, record, :update) end def run_before_destroy_callbacks(record) - controller.send(:before_embedded_destroy, record) + controller.send(:before_embedded, record, :destroy) end end end