in Hacking

Ruby on Rails Json Serialization – To Infinity and beyond!

Wel the title says it all :)

There’s a subtile, but very important difference between Ruby on Rails 3 and 4 with json serialization.

Rails 3

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

Rails 4

(1..10).as_json => "1..10"

I had a piece of Ruby code that modeled the business rules of the application like this:

 
{
  brackets: [
    { income: 0..19_645,               perc: 37 },
    { income: 19_646..55_991,          perc: 42 },
    { income: 55_992..Float::INFINITY, perc: 52 }
  ]
}

Try serializing this to the browser with to_json in Rails 3 and prepare for a long wait ;)

The workaround I used to this was creating an initalizer “/config/initializer/range_to_json_monkey_patch.rb”

#
# This initializer requires some explanation
# 
# In the ruby version installed (Rails 3.2.13)  the json encoding method works like this:
#   ActiveSupport::JSON::encode(1..10)  => [1,2,3,4,5,6,7,8,9,10]
#
# Doing this with a large range  is not nice!!
#
# Ruby on rails 4.0.0.1 works like this:
#   ActiveSupport::JSON::encode(1..10)  => "1..10"
#
# This initializer modifies the Range#as_json method so it works like rails 4
# this method first checks if this adjustment is required
#
if (1..4).as_json.kind_of?(Array)

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

end

Now the json-serialization of Ranges will behave like the one in Rails 4.

Share