Module: JsonapiUtils

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

Overview

TODO:

  1. Create a test suite;

  2. Refactor and separate into submodules;

  3. Include ‘version’ field in the meta node.

Constant Summary collapse

VERSION =
"0.1.1"

Instance Method Summary collapse

Instance Method Details

#jsonapi_error(exception) ⇒ Object



36
37
38
# File 'lib/jsonapi_utils.rb', line 36

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

#jsonapi_render(options) ⇒ Object



14
15
16
17
18
19
# File 'lib/jsonapi_utils.rb', line 14

def jsonapi_render(options)
  if options.has_key?(:json)
    response_body = jsonapi_serialize(options[:json], options[:options] || {})
    render json: response_body, status: (options[:status] || :ok)
  end
end

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



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/jsonapi_utils.rb', line 21

def jsonapi_serialize(records, options = {})
  fix_request_options(params, records)
  results = JSONAPI::OperationResults.new

  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
  create_response_document(results, options).contents
end