Class: Grape::Validations::Types::Json

Inherits:
Object
  • Object
show all
Defined in:
lib/grape/validations/types/json.rb

Overview

Handles coercion and type checking for parameters that are complex types given as JSON-encoded strings. It accepts both JSON objects and arrays of objects, and will coerce the input to a Hash or Array object respectively. In either case the Grape validation system will apply nested validation rules to all returned objects.

Direct Known Subclasses

JsonArray

Instance Method Summary collapse

Instance Method Details

#call(input) ⇒ Hash, ...

Coerce the input into a JSON-like data structure.

Parameters:

  • input (String)

    a JSON-encoded parameter value

Returns:

  • (Hash, Array<Hash>, nil)


19
20
21
22
23
24
25
# File 'lib/grape/validations/types/json.rb', line 19

def call(input)
  return input if coerced?(input)

  # Allow nulls and blank strings
  return if input.nil? || input =~ /^\s*$/
  JSON.parse(input, symbolize_names: true)
end

#coerced?(value) ⇒ true, false

Checks that the input was parsed successfully and isn’t something odd such as an array of primitives.

Parameters:

  • value (Object)

    result of #coerce

Returns:

  • (true, false)


32
33
34
# File 'lib/grape/validations/types/json.rb', line 32

def coerced?(value)
  value.is_a?(::Hash) || coerced_collection?(value)
end