-
Notifications
You must be signed in to change notification settings - Fork 63
/
railtie.rb
66 lines (57 loc) · 1.92 KB
/
railtie.rb
1
2
3
4
5
6
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require 'rails/railtie'
require 'jsonapi/rails/log_subscriber'
require 'jsonapi/rails/renderer'
module JSONAPI
module Rails
# @private
class Railtie < ::Rails::Railtie
MEDIA_TYPE = 'application/vnd.api+json'.freeze
PARSER = lambda do |body|
data = JSON.parse(body)
hash = { _jsonapi: data }
hash.with_indifferent_access
end
RENDERERS = {
jsonapi: SuccessRenderer.new,
jsonapi_errors: ErrorsRenderer.new
}.freeze
initializer 'jsonapi-rails.init' do
register_mime_type
register_parameter_parser
register_renderers
ActiveSupport.on_load(:action_controller) do
require 'jsonapi/rails/controller'
include ::JSONAPI::Rails::Controller
end
end
private
def register_mime_type
Mime::Type.register(MEDIA_TYPE, :jsonapi)
end
def register_parameter_parser
if ::Rails::VERSION::MAJOR >= 5
ActionDispatch::Request.parameter_parsers[:jsonapi] = PARSER
else
ActionDispatch::ParamsParser::DEFAULT_PARSERS[Mime[:jsonapi]] = PARSER
end
end
# rubocop:disable Metrics/MethodLength
def register_renderers
ActiveSupport.on_load(:action_controller) do
RENDERERS.each do |name, renderer|
::ActionController::Renderers.add(name) do |resources, options|
# Renderer proc is evaluated in the controller context.
self.content_type ||= Mime[:jsonapi]
ActiveSupport::Notifications.instrument('render.jsonapi-rails',
resources: resources,
options: options) do
renderer.render(resources, options, self).to_json
end
end
end
end
end
# rubocop:enable Metrics/MethodLength
end
end
end