Sha256: 5b1bbd69679728b36f58c8c59244b061dd4d1ee3cdb65055f028249713764715

Contents?: true

Size: 1.44 KB

Versions: 30

Compression:

Stored size: 1.44 KB

Contents

# frozen_string_literal: true
unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
  require 'json'
end
begin
  require 'ostruct'
rescue LoadError
end

class OpenStruct

  # See #as_json.
  def self.json_create(object)
    new(object['t'] || object[:t])
  end

  # Methods <tt>OpenStruct#as_json</tt> and +OpenStruct.json_create+ may be used
  # to serialize and deserialize a \OpenStruct object;
  # see Marshal[https://docs.ruby-lang.org/en/master/Marshal.html].
  #
  # \Method <tt>OpenStruct#as_json</tt> serializes +self+,
  # returning a 2-element hash representing +self+:
  #
  #   require 'json/add/ostruct'
  #   x = OpenStruct.new('name' => 'Rowdy', :age => nil).as_json
  #   # => {"json_class"=>"OpenStruct", "t"=>{:name=>'Rowdy', :age=>nil}}
  #
  # \Method +JSON.create+ deserializes such a hash, returning a \OpenStruct object:
  #
  #   OpenStruct.json_create(x)
  #   # => #<OpenStruct name='Rowdy', age=nil>
  #
  def as_json(*)
    klass = self.class.name
    klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!"
    {
      JSON.create_id => klass,
      't'            => table,
    }
  end

  # Returns a JSON string representing +self+:
  #
  #   require 'json/add/ostruct'
  #   puts OpenStruct.new('name' => 'Rowdy', :age => nil).to_json
  #
  # Output:
  #
  #   {"json_class":"OpenStruct","t":{'name':'Rowdy',"age":null}}
  #
  def to_json(*args)
    as_json.to_json(*args)
  end
end if defined?(::OpenStruct)

Version data entries

30 entries across 30 versions & 5 rubygems

Version Path
es_cli-0.1.0 vendor/bundle/ruby/3.1.0/gems/json-2.9.1/lib/json/add/ostruct.rb
talon_one-7.0.0 .github/.example/vendor/bundle/ruby/3.3.0/gems/json-2.8.2/lib/json/add/ostruct.rb
json-2.9.1 lib/json/add/ostruct.rb
json-2.9.1-java lib/json/add/ostruct.rb
json-2.9.0 lib/json/add/ostruct.rb
json-2.9.0-java lib/json/add/ostruct.rb
cloudsmith-api-2.0.16 vendor/bundle/ruby/2.6.0/gems/json-2.7.6/lib/json/add/ostruct.rb
json-2.8.2-java lib/json/add/ostruct.rb
json-2.8.2 lib/json/add/ostruct.rb
json-2.8.1 lib/json/add/ostruct.rb
json-2.8.1-java lib/json/add/ostruct.rb
json-2.8.0 lib/json/add/ostruct.rb
json-2.8.0-java lib/json/add/ostruct.rb
json-2.8.0.alpha1 lib/json/add/ostruct.rb
json-2.7.6-java lib/json/add/ostruct.rb
json_pure-2.7.6 lib/json/add/ostruct.rb
json-2.7.6 lib/json/add/ostruct.rb
json_pure-2.7.5 lib/json/add/ostruct.rb
json-2.7.5 lib/json/add/ostruct.rb
json-2.7.5-java lib/json/add/ostruct.rb