Class: IknowParams::Serializer::JsonWithSchema

Inherits:
IknowParams::Serializer show all
Defined in:
lib/iknow_params/serializer.rb,
lib/iknow_params/serializer.rb

Overview

Adds Rails conveniences

Direct Known Subclasses

Rails

Defined Under Namespace

Classes: Rails

Instance Attribute Summary collapse

Attributes inherited from IknowParams::Serializer

#clazz

Instance Method Summary collapse

Methods inherited from IknowParams::Serializer

for, for!, json_value?, #matches_type!, singleton

Constructor Details

#initialize(schema, validate_schema: true) ⇒ JsonWithSchema

Returns a new instance of JsonWithSchema.



260
261
262
263
264
# File 'lib/iknow_params/serializer.rb', line 260

def initialize(schema, validate_schema: true)
  @schema          = schema
  @validate_schema = validate_schema
  super(nil)
end

Instance Attribute Details

#schemaObject (readonly)

Returns the value of attribute schema.



259
260
261
# File 'lib/iknow_params/serializer.rb', line 259

def schema
  @schema
end

Instance Method Details

#dump(val, json: false) ⇒ Object



274
275
276
277
278
279
280
281
# File 'lib/iknow_params/serializer.rb', line 274

def dump(val, json: false)
  matches_type!(val)
  if json
    val
  else
    JSON.dump(val)
  end
end

#load(structure) ⇒ Object



266
267
268
269
270
271
272
# File 'lib/iknow_params/serializer.rb', line 266

def load(structure)
  structure = JSON.parse(structure) if structure.is_a?(::String)
  matches_type!(structure, err: LoadError)
  structure
rescue JSON::ParserError => ex
  raise LoadError.new("Invalid JSON: #{ex.message}")
end

#matches_type?(val) ⇒ Boolean

Returns:



283
284
285
# File 'lib/iknow_params/serializer.rb', line 283

def matches_type?(val)
  JSON::Validator.validate(schema, val, validate_schema: @validate_schema)
end