Skip to content

Instantly share code, notes, and snippets.

@rodrigomanhaes
Created March 17, 2019 23:13
Show Gist options
  • Save rodrigomanhaes/ff4fd5b5d4ad9acbe60f86c0391d99b7 to your computer and use it in GitHub Desktop.
Save rodrigomanhaes/ff4fd5b5d4ad9acbe60f86c0391d99b7 to your computer and use it in GitHub Desktop.
Processing data from audited gem (only a draft)
module AuditDecorator
def changes_with_associations
klass = auditable.class
audited_changes.map do |attribute, (from, to)|
attribute = attribute.to_s
if attribute.ends_with?('_id')
results = from_to(attribute, from, to)
if results.present?
from, to = results
attribute = attribute[0..-4]
end
end
[klass.human_attribute_name(attribute).downcase, [from, to]]
end.to_h
end
private
def from_to(attribute, from, to)
klass = auditable.class
association_class = get_association_class(klass, attribute)
return unless association_class.present?
from = sthem(find_association(association_class, from)) if from.present?
to = sthem(find_association(association_class, to)) if to.present?
[from, to]
end
def find_association(association_class, id)
association_class.find(id)
rescue ActiveRecord::RecordNotFound
audit = Audited::Audit.find_by(
auditable_type: association_class.name, auditable_id: id,
action: 'destroy')
association_class.new(audit.audited_changes) if audit.present?
end
def get_association_class(klass, attribute)
association = klass.
reflect_on_all_associations.find {|a| a.foreign_key == attribute.to_s }
return unless association.present?
association_class_name =
association.options[:class_name] || attribute[0..-4].camelize
association_class_name.constantize
end
def sthem(obj)
result = obj.respond_to?(:to_audit_string) ? obj.to_audit_string : obj.to_s
if obj.is_a?(ActiveRecord::Base) && obj.new_record?
result += ' <excluído>'
end
result
end
end
module Audited
class AuditSerializer < ActiveModel::Serializer
attributes :id, :created_at, :user_email, :i18n_action, :action, :changes
def created_at
object.created_at.strftime('%d/%m/%Y %H:%M')
end
def user_email
object.user&.email
end
def i18n_action
I18n.t("audited.actions.#{object.action}")
end
def changes
object.changes_with_associations.map do |field, (from, to)|
object.action == 'update' ? update(field, from, to) : create(field, from)
end
end
private
def update(field, from, to)
{
attribute: field,
from: from,
to: to
}
end
def create(field, data)
{
attribute: field,
data: data
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment