Skip to content

as_json not called on subclasses of Array/Hash #978

@bquorning

Description

@bquorning

Depending on whether Oj::Rails::Encoder is initialized with an argument or not, Oj does not call #as_json on subclasses of Array and Hash.

require "active_support"
require "oj"

Oj.optimize_rails

class ArraySubclass < Array
  def as_json(options = {})
    %w[array subclass]
  end
end

value = ArraySubclass.new
puts Oj::Rails::Encoder.new({}).encode(value)
# => ["array","subclass"]
puts Oj::Rails::Encoder.new().encode(value)
# => []

class HashSubclass < Hash
  def as_json(options = {})
    {hash: "subclass"}
  end
end

value = HashSubclass.new
puts Oj::Rails::Encoder.new({}).encode(value)
# => {"hash":"subclass"}
puts Oj::Rails::Encoder.new(nil).encode(value)
# => {}

Based on https://github.com/ohler55/oj/blob/develop/pages/Rails.md I would expect Array and Hash to be optimized, but not their subclasses.

We noticed this issue after rails/rails@6204a55 got added to Rails, and started getting everything serialized by Encoding.encode_without_option which uses an instance of Oj::Rails::Encoder created without arguments.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions