rails模型的审计功能

时间:2016-07-24 09:49:57

标签: ruby-on-rails activerecord

我正在尝试为我的某些rails模型实现审计功能,并将其存储在外部“事件”数据库中(我们选择了BigQuery)。

每个活动都应该非常基础: before_json,after_json,diff,action,object_id

所以,我开始构建这个我正计划添加到我的模型中的问题:

module Auditable
  extend ActiveSupport::Concern

  included do

    before_destroy {audit(:destroy)}

    after_validation on: :update do
      audit(:update)
    end

    after_validation on: :create do
      audit(:create)
    end

    def audit(action)
      EventSender.send(before_json, self.to_json, diff, action, self.id)
    end
  end
end

我唯一不知道如何实现的是获取对象的before状态,以便我可以填充相关字段和两种状态之间的差异。

关于我如何做到的任何想法?

1 个答案:

答案 0 :(得分:0)

我通过以下方式解决了这个问题:

module Auditable
  require 'active_record/diff'

  extend ActiveSupport::Concern

  included do
    include ActiveRecord::Diff

    before_destroy {audit(:destroy, before: before_state)}

    after_validation on: :update do
      audit(:update, before: before_state, after: self)
    end

    after_create do
      audit(:create, after: self)
    end

    def audit(action, before: {}, after: {})
      diff = case action
             when :update
               before.diff(after)
             when :create
               after
             when :destroy
               before
             end

      BigQueryClient.new.insert(
        self.class.to_s.downcase,
        {
          before: before.to_json,
          after: after.to_json,
          diff: diff.to_json,
          action: action,
          "#{self.class.to_s.downcase.to_sym}_id": self.id
        },
        dataset_name: "audit"
      )
    end

    private

    def before_state
      self.class.find(self.id)
    end
  end
end

请注意,我使用名为" activerecord-diff"的外部宝石。计算前后之间的差异。