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

Range.as_json #4239

Closed
gurgeous opened this issue Dec 31, 2011 · 6 comments
Closed

Range.as_json #4239

gurgeous opened this issue Dec 31, 2011 · 6 comments

Comments

@gurgeous
Copy link

This scares me:

>> (1..9).as_json
[1,2,3,4,5,6,7,8,9]

Wouldn't this be preferable?

class Range
  def as_json(options = nil)
    to_s
  end
end

This is an issue in my Rails app, where I occasionally return Ranges as JSON. If the wrong Range slips in there it could crash the app in a nasty, un-debuggable way.

@tenderlove
Copy link
Member

What JSON engine are you using? The JSON gem that ships with ruby does not have this behavior:

$ irb
irb(main):001:0> require 'json'
=> true
irb(main):002:0> JSON.dump([1..10])
=> "[\"1..10\"]"
irb(main):003:0>

@gurgeous
Copy link
Author

I'm using Rails 3.1.1 with json 1.6.1 on 1.8.7. I think the problem is caused by active_support/json/encoding.rb:

module Enumerable
  def as_json(options = nil) #:nodoc:
    to_a.as_json(options)
  end
end

Am I doing something wrong? I vaguely remember that the json gem is only required for 1.8.7, so perhaps this issue goes away with 1.9/Rails 4.

Thanks Aaron.

@fxn
Copy link
Member

fxn commented Dec 31, 2011

The problem with calling #to_a is that ranges may be (conceptually) infinite, regardless of whether they respond to succ.

@gurgeous
Copy link
Author

I agree - that's the bug I'm describing.

@lest
Copy link
Contributor

lest commented Jan 2, 2012

@fxn I've changed as_json on Range in #4250

@arunagw
Copy link
Member

arunagw commented Jan 3, 2012

Closing this as #4250 is merged.

Thanks!

@arunagw arunagw closed this as completed Jan 3, 2012
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

5 participants