Created
January 5, 2009 06:40
-
-
Save stefanpenner/43287 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module StefansAssignment | |
def self.included(base) | |
base.class_eval do | |
extend ClassMethods | |
include InstanceMethods | |
end | |
end | |
module ClassMethods | |
def model_accesible(*models) | |
models.each do |model| | |
model_name = model.to_s.downcause.singularize | |
new_model_name = "new_#{model_name}_attributes" | |
existing_model_name = "existing_#{model_name}_attributes" | |
save_method_name = "save_#{model_name.pluralize}" | |
instance_eval "model_collection = #{model_name.pluralize}" | |
define_method "#{new_model_name}=" do |collection| | |
collection.each do |instance| | |
model_collection.build(instance) | |
end | |
end | |
define_method "#{existing_model_name}=" do |name| | |
model_collection.reject(&:new_record?).each do |instance| | |
attributes = collection[instance.id.to_s] | |
if attributes | |
instance.attributes = attributes | |
else | |
model_collection.delete(instance) | |
end | |
end | |
end | |
define_mthod save_method_name do | |
model.collection.each do |instance| | |
instance.save(false) | |
end | |
end | |
attr_accessible new_model_name, existing_model_name | |
after_update save_method_name | |
end | |
end | |
end | |
module InstanceMethods | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment