Sha256: aec08a47f9322ed2808c3c4428cf3c140ff3ef280974f54da998e947f93f6f42

Contents?: true

Size: 959 Bytes

Versions: 21

Compression:

Stored size: 959 Bytes

Contents

module Flexite
  module WithHistory
    extend ActiveSupport::Concern

    included do
      after_save :save_history

      def self.history_attributes(*attributes)
        define_method :history_attributes do
          attributes
        end
      end
    end

    def restore(history)
      history.history_attributes.each do |attr|
        self[attr.name] = attr.value
      end

      self.class.skip_callback(:save, :after, :save_history)

      begin
        save!
      ensure
        self.class.set_callback(:save, :after, :save_history)
      end
    end

    private

    def save_history
      return unless changed?

      history = histories.build

      History.transaction do
        history_attributes.each do |attr|
          history.history_attributes.build(name: attr, value: self[attr])
        end

        history.save
      end

      if history.invalid?
        errors.set(:history, history.full_messages)
      end
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
flexite-0.0.25 app/models/concerns/flexite/with_history.rb
flexite-0.0.24 app/models/concerns/flexite/with_history.rb
flexite-0.0.23 app/models/concerns/flexite/with_history.rb
flexite-0.0.22 app/models/concerns/flexite/with_history.rb
flexite-0.0.21 app/models/concerns/flexite/with_history.rb
flexite-0.0.20 app/models/concerns/flexite/with_history.rb
flexite-0.0.19 app/models/concerns/flexite/with_history.rb
flexite-0.0.18 app/models/concerns/flexite/with_history.rb
flexite-0.0.17 app/models/concerns/flexite/with_history.rb
flexite-0.0.16 app/models/concerns/flexite/with_history.rb
flexite-0.0.15 app/models/concerns/flexite/with_history.rb
flexite-0.0.14 app/models/concerns/flexite/with_history.rb
flexite-0.0.13 app/models/concerns/flexite/with_history.rb
flexite-0.0.12 app/models/concerns/flexite/with_history.rb
flexite-0.0.11 app/models/concerns/flexite/with_history.rb
flexite-0.0.10 app/models/concerns/flexite/with_history.rb
flexite-0.0.9 app/models/concerns/flexite/with_history.rb
flexite-0.0.8 app/models/concerns/flexite/with_history.rb
flexite-0.0.7 app/models/concerns/flexite/with_history.rb
flexite-0.0.6 app/models/concerns/flexite/with_history.rb