Skip to content
This repository

#as_json options seem to stick around when rendering hash as JSON #8182

Closed
docstun opened this Issue · 1 comment

3 participants

Manuel Boy Carlos Antonio da Silva Yves Senn
Manuel Boy

Hey there,

I think there might be a problem when rendering a hash as json that includes an object which implements the #as_json method.

The following spec fails:

require "active_support/all"
require "rspec"

class Foo
  attr_accessor :foo, :bar

  def as_json(options={})
    options[:only] = %w(foo bar)
    super(options)
  end
end

describe "#to_json" do
  it "should render an object with as_json and a hash with all of its attributes" do
    f = Foo.new
    f.foo = "hello"
    f.bar = "world"

    hash = {"foo" => f, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}}
    JSON.parse(hash.to_json).should == {"foo" => {"foo" => "hello", "bar" => "world"}, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}}
  end
end

However it works when the Foo instance is rendered after the hash:

describe "#to_json" do
  it "should render an object with as_json and a hash with all of its attributes" do
    f = Foo.new
    f.foo = "hello"
    f.bar = "world"

    hash = {"other_hash" => {"foo" => "other_foo", "test" => "other_test"}, "foo" => f}
    JSON.parse(hash.to_json).should == {"foo" => {"foo" => "hello", "bar" => "world"}, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}}
  end
end

What do you guys think?

Best,
Manuel

Yves Senn senny referenced this issue from a commit
Commit has since been removed from the repository and is no longer available.
Yves Senn
Collaborator

I think this is a bug, I submitted a PR #8185

Yves Senn senny referenced this issue from a commit
Commit has since been removed from the repository and is no longer available.
Yves Senn senny referenced this issue from a commit
Commit has since been removed from the repository and is no longer available.
Carlos Antonio da Silva carlosantoniodasilva closed this issue from a commit
Yves Senn `#as_json` isolates options when encoding a hash. Closes #8182
Setting options in a custom `#as_json` method had side effects.
Modifications of the `options` hash leaked outside and influenced
the conversion of other objects contained in the hash.
78dca35
Carlos Antonio da Silva carlosantoniodasilva closed this in 78dca35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.