Sha256: 3919468d0f9cd0c8324010ec70fa3d1baa998a84f36c5e5545afcd9f34a3b346

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 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

1 entries across 1 versions & 1 rubygems

Version Path
track_changes-0.5.1 lib/track_changes/filter.rb