Module: ChrnoAudit::ActiveRecordConcern::ClassMethods

Defined in:
lib/chrno_audit/active_record_concern.rb

Instance Method Summary collapse

Instance Method Details

#audit(*fields) ⇒ Object

Макрос добавляет в модель аудит изменений.

Examples:

audit :all, :except => :foo

Parameters:

  • fields (Symbol)

    список полей для аудита (по умолчанию все поля). Можно использовать псевдо-поле :all если необходим аудит всех полей.

  • options (Hash)

    параметры аудита @option options [Array] :except ([])

    @option options [Array] :when ([ :create, :update, :destroy ])

    @option [true, false] :ignore_empty_diff (true)



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/chrno_audit/active_record_concern.rb', line 32

def audit( *fields )
  # Если таблицы ещё нет, ничего не делаем (полезно для миграций)
  unless table_exists?
    self.logger.warn "Audit: try to audit model [#{name}] with non-existent table" if self.logger
    return
  end

  # Добавляем связь
  has_many :audit_records, :as => :auditable, :class_name => "ChrnoAudit::AuditRecord"

  # Добавляем обсервер
  ChrnoAudit::AuditObserver.attach( self )

  # Добавляем необходимые параметры
  cattr_accessor :auditable_fields, :auditable_actions, :auditable_options

  options = fields.extract_options!

  # Настройки по умолчанию
  options.reverse_merge! \
    :except            => [],
    :when              => [ :create, :update, :destroy ],
    :ignore_empty_diff => true

  # Нормализуем параметры
  options[ :except ] = Array.wrap( options[ :except ] ).map( &:to_s   )
  options[ :when   ] = Array.wrap( options[ :when   ] ).map( &:to_sym )

  # Получаем список полей.
  self.auditable_fields =
    # Аудит на всех полях?
    if fields.count == 1 and fields.first == :all
      # Всегда выкидываем timestamp и id.
      column_names - %W{ id created_at updated_at } - options[ :except ]
    else
      ( fields - options.delete( :except )).map( &:to_s )
    end

  self.auditable_actions = options.delete( :when )
  self.auditable_options = options

  # Проверки
  if self.logger
    self.logger.warn "Audit: no fields to audit" if self.auditable_fields.empty?
    self.logger.warn "Audit: no actions to audit" if self.auditable_actions.empty?
  end
end