Range.as_json #4239

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

Projects

None yet

5 participants

@gurgeous

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
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

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
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

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

@lest
Contributor
lest commented Jan 2, 2012

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

@arunagw
Member
arunagw commented Jan 3, 2012

Closing this as #4250 is merged.

Thanks!

@arunagw arunagw closed this Jan 3, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment