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

Closed
docstun opened this Issue Nov 12, 2012 · 1 comment

Comments

Projects
None yet
3 participants

docstun commented Nov 12, 2012

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

Member

senny commented Nov 12, 2012

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

carlosantoniodasilva added a commit that referenced this issue Nov 13, 2012

Merge pull request #8185 from senny/8182_as_json_options_stick_around
`#as_json` isolates options when encoding a hash. Closes #8182
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment