Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module MiniForm::Associations
- extend ActiveSupport::Concern
- included do
- validate do
- associations.validate_into(errors)
- end
- after_update do
- association.save
- end
- end
- module ClassMethods
- # association :model, :name, attributes: %i(id name for)
- # TODO: single assoc
- # TODO(rstankov): validate values
- # TODO options: allow_new, allow_destroy
- def association(model_name, association_name, attributes:, allow_new: true, allow_destroy: true)
- define_method(association_name) do
- public_send(model_name).public_send(association_name)
- end
- define_method(association_name) do |values|
- associations.assign(public_send(model_name).public_send(association_name), values)
- end
- end
- end
- private
- def associations
- @associations ||= Associations.new
- end
- class Associations
- def initialize
- @to_save ||= []
- end
- def assign(assoc, values)
- record = assoc.detect { |r| r.id === values[:id] } if values[:id]
- record ||= assoc.new
- if values[:_destroy]
- record.marked_for_destruction
- else
- record.attributes = values
- end
- to_save << record
- record
- end
- def validate_into(errors)
- to_save.reject(&:marked_for_destruction).select(&:invalid).each do |record|
- # TODO(rstankov): ADD errors
- errors.add :todo, :invalid
- end
- end
- def save
- to_save.each do |record|
- if record.marked_for_destruction?
- record.destroy!
- else
- record.save!
- end
- end
- end
- private
- attr_reader :to_save
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement