Class: JSONAPI::Utils::Exceptions::ActiveRecord

Inherits:
Exceptions::Error
  • Object
show all
Defined in:
lib/jsonapi/utils/exceptions/active_record.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, resource_klass, context) ⇒ JSONAPI::Utils::Exceptions::ActiveRecord

Construct an error decorator over ActiveRecord objects.

Parameters:

  • object (ActiveRecord::Base)

    Invalid ActiveRecord object. e.g.: User.new(name: nil).tap(&:save)

  • resource_klass (JSONAPI::Resource)

    Resource class to be used for reflection. e.g.: UserResuource



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/jsonapi/utils/exceptions/active_record.rb', line 18

def initialize(object, resource_klass, context)
  @object   = object
  @resource = resource_klass.new(object, context)

  # Need to reflect on resource's relationships for error reporting.
  @relationships      = resource_klass._relationships.values
  @relationship_names = @relationships.map(&:name).map(&:to_sym)
  @foreign_keys       = @relationships.map(&:foreign_key).map(&:to_sym)
  @resource_key_for   = {}
  @formatted_key      = {}
end

Instance Attribute Details

#foreign_keysObject (readonly)

Returns the value of attribute foreign_keys.



5
6
7
# File 'lib/jsonapi/utils/exceptions/active_record.rb', line 5

def foreign_keys
  @foreign_keys
end

#objectObject (readonly)

Returns the value of attribute object.



5
6
7
# File 'lib/jsonapi/utils/exceptions/active_record.rb', line 5

def object
  @object
end

#relationship_namesObject (readonly)

Returns the value of attribute relationship_names.



5
6
7
# File 'lib/jsonapi/utils/exceptions/active_record.rb', line 5

def relationship_names
  @relationship_names
end

#relationshipsObject (readonly)

Returns the value of attribute relationships.



5
6
7
# File 'lib/jsonapi/utils/exceptions/active_record.rb', line 5

def relationships
  @relationships
end

#resourceObject (readonly)

Returns the value of attribute resource.



5
6
7
# File 'lib/jsonapi/utils/exceptions/active_record.rb', line 5

def resource
  @resource
end

Instance Method Details

#errorsArray

Note:

That’s the method used by formatters to build the response’s error body.

Decorate errors for AR invalid objects.

Returns:

  • (Array)


37
38
39
40
41
42
43
# File 'lib/jsonapi/utils/exceptions/active_record.rb', line 37

def errors
  object.errors.messages.flat_map do |field, messages|
    messages.map.with_index do |message, index|
      build_error(field, message, index)
    end
  end
end