Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON.generate ignores to_json method inside Fixnum or Bignum #254

Closed
sproot opened this issue Aug 12, 2015 · 2 comments
Closed

JSON.generate ignores to_json method inside Fixnum or Bignum #254

sproot opened this issue Aug 12, 2015 · 2 comments

Comments

@sproot
Copy link

sproot commented Aug 12, 2015

Here is an example:

> (1..4).to_json
=> "[\"1..4\"]" 
> JSON.generate [1..4]
=> "[\"1..4\"]" 
class Range
  def to_json(*a)
    {
      'json_class'   => self.class.name, # = 'Range'
      'data'         => [ first, last, exclude_end? ]
    }.to_json(*a)
  end
end
> (1..4).to_json
=> "{\"json_class\":\"Range\",\"data\":[1,4,false]}" 
> JSON.generate [1..4]
=> "[{\"json_class\":\"Range\",\"data\":[1,4,false]}]" 

So to_json works well with Range class. But let's try it with Fixnum

1.to_json
=> "1" 
>  JSON.generate [1]
=> "[1]" 
class Fixnum
  def to_json(*a)
    { value: self.to_s }.to_json(*a)
  end
end
> 1.to_json
=> "{\"value\":\"1\"}" 
>  JSON.generate [1]
=> "[1]" 

WAT? Why do we have different behaviour for integers? :(

@marcandre
Copy link
Member

marcandre commented Jun 30, 2020

I confirm that this bug is still present. It affects the C implementation, but not json/pure. This is due to an optimization that should check if the builtin method has been redefined or not. (did not check Java port)

@byroot
Copy link
Member

byroot commented Oct 18, 2024

I'm afraid checking for that would really kill performance, so while I understand one might expect this behavior, I don't think it's desirable to handle it.

@byroot byroot closed this as not planned Won't fix, can't repro, duplicate, stale Oct 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants