Skip to content

Commit

Permalink
extend logga to model deletions
Browse files Browse the repository at this point in the history
  • Loading branch information
Lorenzo Tello committed Aug 5, 2017
1 parent 0c4633b commit e38a6c0
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions lib/logga/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module Logga
module ActiveRecord
extend ActiveSupport::Concern

EXCLUDED_KEYS = [:created_at, :updated_at, :log, :sent_photos_chaser_email, :sent_after_sales_emails]
EXCLUDED_KEYS = [:created_at, :deleted_at, :updated_at, :log, :sent_photos_chaser_email, :sent_after_sales_emails]
EXCLUDED_KEYS_SUFFIXES = [:_id, :_filenames]

included do
Expand All @@ -12,8 +12,9 @@ module ActiveRecord

class_methods do
def add_log_entries_for(*actions, to: :self, fields: {})
after_create :log_model_creation if actions.include?(:create)
after_update :log_model_changes if actions.include?(:update)
after_create :log_model_creation if actions.include?(:create)
after_destroy :log_model_deletion if actions.include?(:delete)
after_update :log_model_changes if actions.include?(:update)
define_method(:log_receiver) { to == :self ? self : send(to) }
self.log_fields = fields
end
Expand All @@ -25,6 +26,12 @@ def log_model_creation
log_receiver.log_entries.create(author_data.merge(body: body))
end

def log_model_deletion
body_generator = ->(record) {default_deletion_log_body(record)}
body = log_fields.fetch(:deleted_at, body_generator).call(self)
log_receiver.log_entries.create(author_data.merge(body: body))
end

def log_model_changes
field_changes = changes.reject do |k, _|
EXCLUDED_KEYS.include?(k.to_sym) ||
Expand Down Expand Up @@ -62,5 +69,12 @@ def default_creation_log_body(record)
def default_change_log_body(record, field, old_value, new_value)
"#{record.class.name.demodulize.titleize} #{field} set to #{new_value}"
end

def default_deletion_log_body(record)
[
"#{record.class.name.demodulize} removed",
("(#{record.name})" if record.try(:name))
].compact.join(' ')
end
end
end

0 comments on commit e38a6c0

Please sign in to comment.