Module: JSONAPI::Utils

Extended by:
ActiveSupport::Concern
Defined in:
lib/jsonapi/utils.rb,
lib/jsonapi/utils/version.rb

Constant Summary collapse

VERSION =
"0.2.0"

Instance Method Summary collapse

Instance Method Details

#jsonapi_error(exception) ⇒ Object



50
51
52
# File 'lib/jsonapi/utils.rb', line 50

def jsonapi_error(exception)
  JSONAPI::ErrorsOperationResult.new(exception.errors[0].code, exception.errors).as_json
end

#jsonapi_render(options) ⇒ Object



11
12
13
14
15
16
# File 'lib/jsonapi/utils.rb', line 11

def jsonapi_render(options)
  if options.has_key?(:json)
    response = build_response(options)
    render json: response[:body], status: options[:status] || response[:status] || :ok
  end
end

#jsonapi_render_not_foundObject



18
19
20
# File 'lib/jsonapi/utils.rb', line 18

def jsonapi_render_not_found
  jsonapi_render json: nil
end

#jsonapi_render_not_found_with_nullObject



22
23
24
# File 'lib/jsonapi/utils.rb', line 22

def jsonapi_render_not_found_with_null
  jsonapi_render json: nil, options: { allow_null: true }
end

#jsonapi_serialize(records, options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/jsonapi/utils.rb', line 26

def jsonapi_serialize(records, options = {})
  return build_nil if records.nil? && options[:allow_null]
  results = JSONAPI::OperationResults.new

  if records.nil?
    id = extract_ids(@request.params)
    record_not_found = JSONAPI::Exceptions::RecordNotFound.new(id)
    results.add_result(JSONAPI::ErrorsOperationResult.new(record_not_found.errors[0].code, record_not_found.errors))
  else
    fix_request_options(params, records)

    if records.respond_to?(:to_ary)
      records = fix_when_hash(records, options) if records.all? { |e| e.is_a?(Hash) }
      @resources = build_collection(records, options)
      results.add_result(JSONAPI::ResourcesOperationResult.new(:ok, @resources, result_options(options)))
    else
      @resource = turn_into_resource(records, options)
      results.add_result(JSONAPI::ResourceOperationResult.new(:ok, @resource))
    end
  end

  create_response_document(results).contents
end