Sha256: ccc0112a3b9d4f979e8826d3db7b3231d9dc7b7b20856d7c838f4c4509c9b917

Contents?: true

Size: 1.06 KB

Versions: 6

Compression:

Stored size: 1.06 KB

Contents

require 'track_changes/result'

module TrackChanges
  class Filter
    attr_accessor :call_proc, :changes, :model, :original

    def initialize(model, yield_only_changed, call_proc)
      @call_proc = call_proc
      @model = model
      @yield_only_changed = yield_only_changed
      @changes = []
      @original = []
    end

    def before(controller)
      @original = clone_model(controller)
    end

    def after(controller)
      cur_model = controller.instance_variable_get("@#{@model}")
      # If changed? returns true, then the update didn't succeed.
      unless cur_model.changed?
        @changes = changes_between(@original, cur_model)
        unless @yield_only_changed && @changes.empty?
          @call_proc.call(Result.new(@model, controller, @changes))
        end
      end
      nil
    end

    private

    def changes_between(old, new)
      old.attributes = new.attributes
      old.changes
    end

    def clone_model(controller)
      ivar = controller.instance_variable_get("@#{@model}")
      ivar.clone if ivar.respond_to?(:clone)
    end
  end
end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
smajn-track_changes-0.3.0 lib/track_changes/filter.rb
track_changes-0.5.0 lib/track_changes/filter.rb
track_changes-0.4.1 lib/track_changes/filter.rb
track_changes-0.4.0 lib/track_changes/filter.rb
track_changes-0.3.2 lib/track_changes/filter.rb
track_changes-0.3.0 lib/track_changes/filter.rb