module Arkaan::Concerns::Historizable

This module is what I call “a beautiful piece of Ruby engineering” It takes any mongoid field that you may have declared, and historizes it in a dedicated relation if this relation does not already exists.

What it does exactly :

@author Vincent Courtois <courtois.vincent@outlook.com>

Public Instance Methods

add_history(field:, from:, to:) click to toggle source

Adds an entry in the history table for the given field. It checks several things to make the history entry valid :

  • the new value is different from the old value

  • the old value is identical to the last recorded new value.

@param field [String] the name of the field to historize @param from [Any] the old value before update @param to [Any] the new value after update.

# File lib/arkaan/concerns/historizable.rb, line 27
def add_history(field:, from:, to:)
  return if from == to
  return if !history.empty? && history.order_by(:created_at.desc).first.to != from

  event = Arkaan::Event.create(field: field, from: from, to: to, document: self)
  event.save
end