Module: Guts::TrackableConcern::ClassMethods

Defined in:
app/concerns/guts/trackable_concern.rb

Overview

Class methods for this concern

Instance Method Summary collapse

Instance Method Details

#trackable(*types, **opts) ⇒ Object

Note:

This uses ‘self.changes` from ActiveRecord to track fields

Tracks changes to a model

Examples:

Example for Category model

# Will track create and update, as well as title changes
trackable :create, :update, fields: [:title]

Parameters:

  • types (Array)

    an array of callbacks to watch from ActiveRecord

  • opts (Hash)

    options for the tracker

Options Hash (**opts):

  • :fields (Array)

    list of fields to track changes on



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'app/concerns/guts/trackable_concern.rb', line 16

def trackable(*types, **opts)
  # Loop over each type
  types.each do |type|
    # Start the callback on this modal
    send :"after_#{type}" do
      params = {}

      # Check if we're watching for a specific field
      if opts[:fields] && type == :update
        # They do... grab those changes and merge them into our params
        params = 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