Module: ActiveRecordAuditable::ActsAsJson::ClassMethods

Defined in:
app/models/concerns/active_record_auditable/acts_as_json.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_json(attribute_name) ⇒ Object

rubocop:disable Metrics/PerceivedComplexity



7
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
40
41
42
43
44
45
46
47
# File 'app/models/concerns/active_record_auditable/acts_as_json.rb', line 7

def acts_as_json(attribute_name) # rubocop:disable Metrics/PerceivedComplexity
  return if ActiveRecordAuditable::Audit.connection.class.name.include?("SQLite")

  serialize attribute_name, coder: JSON

  validate do
    value = __send__(attribute_name)

    if value.is_a?(String)
      begin
        JSON.parse(value)
      rescue JSON::ParserError
        errors.add(attribute_name, :invalid)
      end
    end
  end

  define_method(attribute_name) do
    value = super()

    if value.is_a?(String) && value.present?
      JSON.parse(value)
    else
      value
    end
  rescue JSON::ParserError
    super()
  end

  define_method(:"#{attribute_name}=") do |new_value|
    if new_value.is_a?(Hash)
      super(JSON.generate(new_value))
    elsif new_value.is_a?(String) && new_value.blank?
      super(nil)
    else
      super(new_value)
    end
  rescue JSON::ParserError
    super(new_value)
  end
end