module Kushojin::ModelMethods::Callback::ClassMethods

Public Class Methods

extended(klass) click to toggle source
# File lib/kushojin/model_methods/callback.rb, line 7
def self.extended(klass)
  klass.class_attribute :kushojin_callbacks, instance_accessor: false
end

Public Instance Methods

record_changes(callbacks = nil, only: []) click to toggle source

Record changes of the ActiveRecord model.

class User < ApplicationRecord
  record_changes
end

You can pass in a class or an instance to change behaviors of the callbacks.

class CustomCallbacks
  # Must be able to respond to after_create, after_update, and after_destroy.
  def after_create(record); end
  def after_update(record); end
  def after_destroy(record); end
end

class User < ApplicationRecord
  record_changes CustomCallbacks.new
end

Changes is recorded when the model is created, updated and destroyed. The :only option can be used same as filters of controller.

record_changes only: [:create, :destroy]
Options
  • only - Records only for this event. Support event is :create, :update, and :destroy.

# File lib/kushojin/model_methods/callback.rb, line 40
def record_changes(callbacks = nil, only: [])
  if kushojin_callbacks
    remove_callbacks
    self.kushojin_callbacks = callbacks if callbacks
  else
    self.kushojin_callbacks = callbacks || RecordChangesCallbacks.new
  end

  record_events = convert_to_record_events(only)
  record_events.each do |event|
    public_send(event, kushojin_callbacks)
  end
end

Private Instance Methods

remove_callbacks() click to toggle source
# File lib/kushojin/model_methods/callback.rb, line 56
def remove_callbacks
  kind_and_names =
    RECORD_EVENTS.map { |event| event.to_s.split("_", 2).map(&:to_sym) }

  kind_and_names.each do |kind, name|
    skip_callback(name, kind, kushojin_callbacks, raise: false)
  end
end