Skip to content

Instantly share code, notes, and snippets.

@stefanpenner
Created January 5, 2009 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanpenner/43287 to your computer and use it in GitHub Desktop.
Save stefanpenner/43287 to your computer and use it in GitHub Desktop.
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