Module: Hanami::Action::BodyParser Private

Defined in:
lib/hanami/action/body_parser.rb,
lib/hanami/action/body_parser/json.rb,
lib/hanami/action/body_parser/multipart_form.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Parses request bodies based on the action’s accepted formats.

Since:

  • 0.1.0

Defined Under Namespace

Modules: JSON, MultipartForm

Constant Summary collapse

FALLBACK_KEY =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Since:

  • 0.1.0

:_

Class Method Summary collapse

Class Method Details

.parse(env, config) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Parses the request body if applicable

Parameters:

Since:

  • 0.1.0



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
# File 'lib/hanami/action/body_parser.rb', line 23

def parse(env, config)
  # If the router has already parsed the body, derive our own keys from it.
  if env.key?(ROUTER_PARSED_BODY)
    parsed = env[ROUTER_PARSED_BODY]
    env[ACTION_PARSED_BODY] = parsed
    env[ACTION_BODY_PARAMS] = symbolize_body(parsed)
    return
  end

  return if env.key?(ACTION_PARSED_BODY)

  input = env[::Rack::RACK_INPUT]
  return unless input

  media_type = Mime.extract_media_type(env[CONTENT_TYPE])
  return unless media_type

  if config.formats.empty?
    # When no format is explicity configured, parse multipart/form-data bodies as a sensible
    # default. These kinds of form submissions are a standard part of standard web behavior,
    # and users expect them to work out of the box.
    return unless media_type == "multipart/form-data"
  else
    return unless Mime.accepted_content_type?(media_type, config)
  end

  parser = config.formats.body_parser_for(media_type)
  return unless parser

  input = ensure_rewindable_input(env)
  body = read_body(input)
  return if body.nil? || body.empty?

  # Pass both the body string and the Rack env to the parser. Most parsers should only need
  # the body, but the env is there in case access to headers or calling Rack APIs is
  # required.
  parsed = parser.call(body, env)

  env[ACTION_PARSED_BODY] = parsed
  env[ACTION_BODY_PARAMS] = symbolize_body(parsed)
end