Sha256: d9fcb0dc9aaac8390d2317eb98e47f52fd1c968a0eebbea3b7352fa92f8ba406

Contents?: true

Size: 1.33 KB

Versions: 4

Compression:

Stored size: 1.33 KB

Contents

module Guts
  # Handles tracking model changes through callbacks
  module TrackableConcern
    extend ActiveSupport::Concern
    
    # Class methods for this concern
    module ClassMethods
      # Tracks changes to a model
      # @param [Array] types an array of callbacks to watch from ActiveRecord
      # @param [Hash] opts options for the tracker
      # @option opts [Array] :fields list of fields to track changes on
      # @example Example for Category model
      #   # Will track create and update, as well as title changes
      #   trackable :create, :update, fields: [:title]
      # @note This uses `self.changes` from ActiveRecord to track fields
      def trackable(*types, **opts)
        # Loop over each type
        types.each do |type|
          # Start the callback on this modal
          self.send :"after_#{type}" do
            params = {}

            # Check if we're watching for a specific field
            if opts[:fields] and type == :update
              # They do... grab those changes and merge them into our params
              params = self.changes.select {|field| opts[:fields].include? field.to_sym}
            end
            
            # Finally, complete the track to the database if allowed
            Tracker.create(action: type, object: self, params: params)
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
guts-1.0.8 app/concerns/guts/trackable_concern.rb
guts-1.0.7 app/concerns/guts/trackable_concern.rb
guts-1.0.5 app/concerns/guts/trackable_concern.rb
guts-1.0.3 app/concerns/guts/trackable_concern.rb