Method: JSON::Coder#initialize

Defined in:
lib/json/common.rb

#initialize(options = nil, &as_json) ⇒ Coder

:call-seq:

JSON.new(options = nil, &block)

Argument options, if given, contains a Hash of options for both parsing and generating. See Parsing Options, and Generating Options.

For generation, the strict: true option is always set. When a Ruby object with no native JSON counterpart is encoutered, the block provided to the initialize method is invoked, and must return a Ruby object that has a native JSON counterpart:

module MyApp
  API_JSON_CODER = JSON::Coder.new do |object|
    case object
    when Time
      object.iso8601(3)
    else
      object # Unknown type, will raise
    end
  end
end

puts MyApp::API_JSON_CODER.dump(Time.now.utc) # => "2025-01-21T08:41:44.286Z"


1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
# File 'lib/json/common.rb', line 1020

def initialize(options = nil, &as_json)
  if options.nil?
    options = { strict: true }
  else
    options = options.dup
    options[:strict] = true
  end
  options[:as_json] = as_json if as_json

  @state = State.new(options).freeze
  @parser_config = Ext::Parser::Config.new(ParserOptions.prepare(options))
end