Skip to content

Refactor parser/deserialization. #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 25, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 5 additions & 21 deletions lib/jsonapi/rails/action_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,29 +32,13 @@ def deserializable_relationship(key, options = {}, &block)
def _deserializable(key, options, fallback, &block)
options = options.dup
klass = options.delete(:class) || Class.new(fallback, &block)
use Deserialization, key, klass, options
end
end

class Deserialization
REQUEST_PARAMETERS_KEY =
'action_dispatch.request.request_parameters'.freeze
def initialize(app, key, klass)
@app = app
@deserializable_key = key
@deserializable_class = klass
end

def call(env)
request = Rack::Request.new(env)
body = JSON.parse(request.body.read)
deserializable = @deserializable_class.new(body)
env[REVERSE_MAPPING_KEY] = deserializable.reverse_mapping
(env[REQUEST_PARAMETERS_KEY] ||= {}).tap do |request_parameters|
request_parameters[@deserializable_key] = deserializable.to_hash
before_action(options) do |controller|
resource = klass.new(controller.params[:_jsonapi].to_unsafe_hash)
controller.request.env[REVERSE_MAPPING_KEY] =
resource.reverse_mapping
controller.params[key.to_sym] = resource.to_hash
end

@app.call(env)
end
end
end
Expand Down
13 changes: 6 additions & 7 deletions lib/jsonapi/rails/parser.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
require 'jsonapi/deserializable'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing frozen string literal comment.


module JSONAPI
module Rails
module_function
PARSER = lambda do |body|
data = JSON.parse(body)
hash = { _jsonapi: data }

def parser
lambda do |body|
data = JSON.parse(body)
data = { _json: data } unless data.is_a?(Hash)
data.with_indifferent_access
end
hash.with_indifferent_access
end
end
end
1 change: 0 additions & 1 deletion lib/jsonapi/rails/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ module JSONAPI
module Rails
class Railtie < ::Rails::Railtie
MEDIA_TYPE = 'application/vnd.api+json'.freeze
PARSER = JSONAPI::Rails.parser
RENDERERS = {
jsonapi: JSONAPI::Rails.rails_renderer(SuccessRenderer),
jsonapi_error: JSONAPI::Rails.rails_renderer(ErrorRenderer)
Expand Down