Class: ModelsAuditor::DefaultFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/models_auditor/default_formatter.rb

Instance Method Summary collapse

Constructor Details

#initialize(collection) ⇒ DefaultFormatter

Returns a new instance of DefaultFormatter.



3
4
5
# File 'lib/models_auditor/default_formatter.rb', line 3

def initialize(collection)
  @collection = collection
end

Instance Method Details

#as_jsonObject

Parameters:



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/models_auditor/default_formatter.rb', line 8

def as_json
  requests =
    case @collection
      when ActiveRecord::Relation
        @collection.to_a
      when ModelsAuditor::AuditRequest
        [@collection]
      when Array
        @collection
      else
        raise ArgumentError('Incorrect type of argument `requests`')
    end

  requests.map do |request|
    records = request.records
    {}.tap do |result|
      changed_models_collection =
        records
          .select { |record| record.bridge.nil? }
          .map do |record|
          {
            data:          record.attributes.slice('id', 'object_type', 'object_id'),
            relationships: get_relations(record, records)
          }
        end

      result[:request]   = request.as_json
      result[:changes_struct] = changed_models_collection.group_by { |i| i[:data]['object_type'] }
      result[:all_changes]    = records.map(&:as_json)
    end
  end
end