Class: JSON::Fragment

Inherits:
Struct
  • Object
show all
Defined in:
lib/json/common.rb

Overview

Fragment of JSON document that is to be included as is:

fragment = JSON::Fragment.new("[1, 2, 3]")
JSON.generate({ count: 3, items: fragments })

This allows to easily assemble multiple JSON fragments that have been persisted somewhere without having to parse them nor resorting to string interpolation.

Note: no validation is performed on the provided string. It is the responsibility of the caller to ensure the string contains valid JSON.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Struct

#as_json, json_create

Constructor Details

#initialize(json) ⇒ Fragment

Returns a new instance of Fragment.



293
294
295
296
297
298
299
# File 'lib/json/common.rb', line 293

def initialize(json)
  unless string = String.try_convert(json)
    raise TypeError, " no implicit conversion of #{json.class} into String"
  end

  super(string)
end

Instance Attribute Details

#jsonObject

Returns the value of attribute json

Returns:

  • (Object)

    the current value of json



292
293
294
# File 'lib/json/common.rb', line 292

def json
  @json
end

Instance Method Details

#to_json(state = nil) ⇒ Object



301
302
303
# File 'lib/json/common.rb', line 301

def to_json(state = nil, *)
  json
end