Sha256: 327b3183aa555d2d5b9df98c00804ed5239a99124d9ca8407993d90fabf47363

Contents?: true

Size: 865 Bytes

Versions: 5

Compression:

Stored size: 865 Bytes

Contents

# encoding: UTF-8

module Spontaneous::Model::Core
  module CascadingChange
    extend Spontaneous::Concern

    module ClassMethods
      def cascading_change(attr_name, &block)
        define_method "#{attr_name}=" do |value|
          append_cascading_change(attr_name, self[attr_name], value, &block)
          super(value)
        end
      end
    end

    private

    def changes_to_cascade
      @changes_to_cascade ||= {}
    end

    def append_cascading_change(attribute, old_value, new_value, &block)
      changes_to_cascade[attribute] = block.call(self, old_value, new_value) if new_value != old_value
    end

    def after_save
      super
      cascade_all_changes
    end

    def cascade_all_changes
      changes_to_cascade.each do |attribute, propagator|
        propagator.propagate
      end
      changes_to_cascade.clear
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
spontaneous-0.2.0.beta10 lib/spontaneous/model/core/cascading_change.rb
spontaneous-0.2.0.beta9 lib/spontaneous/model/core/cascading_change.rb
spontaneous-0.2.0.beta8 lib/spontaneous/model/core/cascading_change.rb
spontaneous-0.2.0.beta7 lib/spontaneous/model/core/cascading_change.rb
spontaneous-0.2.0.beta6 lib/spontaneous/model/core/cascading_change.rb