Module: JSON::TruffleRuby::Generator::GeneratorMethods::Object

Defined in:
lib/json/truffle_ruby/generator.rb

Instance Method Summary collapse

Instance Method Details

#to_json(state = nil) ⇒ Object

Converts this object to a string (calling #to_s), converts it to a JSON string, and returns the result. This is a fallback, if no special method #to_json was defined for some object.



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/json/truffle_ruby/generator.rb', line 423

def to_json(state = nil, *)
  state = State.from_state(state) if state
  if state&.strict?
    value = self
    if state.strict? && !(false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value || Fragment === value)
      if state.as_json
        value = state.as_json.call(value)
        unless false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value || Fragment === value
          raise GeneratorError.new("#{value.class} returned by #{state.as_json} not allowed in JSON", value)
        end
        value.to_json(state)
      else
        raise GeneratorError.new("#{value.class} not allowed in JSON", value)
      end
    end
  else
    to_s.to_json
  end
end