123456789_123456789_123456789_123456789_123456789_

Class: JSON::Fragment

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::Struct
Instance Chain:
self, ::Struct
Inherits: Struct
Defined in: ext/json/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 responsability of the caller to ensure the string contains valid ::JSON.

Class Method Summary

::Struct - Inherited

.json_create

See #as_json.

Instance Attribute Summary

  • #json rw

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

Instance Method Summary

::Struct - Inherited

#as_json

Methods as_json and Struct.json_create may be used to serialize and deserialize a Struct object; see Marshal.

#to_json

Returns a ::JSON string representing self:

Constructor Details

.new(json) ⇒ Fragment

[ GitHub ]

  
# File 'ext/json/lib/json/common.rb', line 181

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

#json (rw)

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 responsability of the caller to ensure the string contains valid ::JSON.

[ GitHub ]

  
# File 'ext/json/lib/json/common.rb', line 180

Fragment = Struct.new(:json)

Instance Method Details

#to_json(state = nil)

[ GitHub ]

  
# File 'ext/json/lib/json/common.rb', line 189

def to_json(state = nil, *)
  json
end