From 90a6ef5ef3875eba9b1b9dafa0fbdb74057af004 Mon Sep 17 00:00:00 2001 From: Neeraj Singh Date: Sun, 10 May 2009 22:57:05 -0400 Subject: [PATCH] adding indent option to the to_json method in Hash --- .../lib/active_support/json/encoders/hash.rb | 14 ++++++++++++-- 1 files changed, 12 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/json/encoders/hash.rb b/activesupport/lib/active_support/json/encoders/hash.rb index 4771484..80e0942 100644 --- a/activesupport/lib/active_support/json/encoders/hash.rb +++ b/activesupport/lib/active_support/json/encoders/hash.rb @@ -20,6 +20,13 @@ class Hash # # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:except => 1) # # => {"name": "Konata Izumi", "age": 16} + # + # The :indent option can be used to ident the output of the data. + # { :name => 'Konata Izumi', :info => {:color => 'white'}}.to_json(:indent => 7) + # # => {"info": + # {"color": "white" }, + # "name": "Konata Izumi"} + # # # The +options+ also filter down to any hash values. This is particularly # useful for converting hashes containing ActiveRecord objects or any object @@ -42,10 +49,13 @@ class Hash end end - result = '{' + space = options[:indent] ? ' ' : '' + result = options[:indent] ? "\r\n{" : "{" + end_of_line_formatter = options[:indent] ? " ,\r\n #{space * (options[:indent])}" : ' ,' + result << hash_keys.map do |key| "#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(self[key], options, *args)}" - end * ',' + end * end_of_line_formatter result << '}' end end -- 1.5.4.5