Sha256: b9d6d42227b6ed6f54c04d49347f3ba63e4216ad7e8b3bd5bd565ea0f4904349

Contents?: true

Size: 1.46 KB

Versions: 5

Compression:

Stored size: 1.46 KB

Contents

class ActiveShepherd::Methods::QueryChanges < ActiveShepherd::QueryMethod
  def query_changes
    traverse!
    set_meta_action
    query
  end

  def handle_attribute(attribute_name, before, after)
    query[attribute_name] = [before, after]
  end

  def handle_has_many_association(reflection)
    association = aggregate.model.send reflection.name

    collection_changes = association.each.with_object({}).with_index do |(associated_model, h), index|
      changes = self.class.query_changes recurse(associated_model, reflection.foreign_key)
      h[index] = changes unless changes.blank?
    end

    unless collection_changes.blank?
      query[reflection.name] = collection_changes
    end
  end

  def handle_has_one_association(reflection)
    associated_model = aggregate.model.send reflection.name
    return unless associated_model.present?

    changes = self.class.query_changes recurse(associated_model, reflection.foreign_key)
    query[reflection.name] = changes unless changes.blank?
  end

  def setup
    super
    @attributes = aggregate.model.changes.each_with_object({}) do |(name,changes),h|
      next if aggregate.excluded_attributes.include? name.to_s
      h[name.to_sym] = changes.map do |raw_value|
        aggregate.serialize_value name, raw_value
      end
    end
  end

private

  def set_meta_action
    if not aggregate.model.persisted?
      query[:_create] = '1'
    elsif aggregate.model.marked_for_destruction?
      query[:_destroy] = '1'
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
activeshepherd-0.8.4 lib/active_shepherd/methods/query_changes.rb
activeshepherd-0.8.3 lib/active_shepherd/methods/query_changes.rb
activeshepherd-0.8.2 lib/active_shepherd/methods/query_changes.rb
activeshepherd-0.8.1 lib/active_shepherd/methods/query_changes.rb
activeshepherd-0.8.0 lib/active_shepherd/methods/query_changes.rb