From 8d1f611225e72139cdc0615fcb79cdb4fb88f234 Mon Sep 17 00:00:00 2001 From: Damien MATHIEU Date: Fri, 6 Feb 2009 14:46:36 +0100 Subject: [PATCH] Add methods to_xml and to_json to OrderedHash. --- activesupport/lib/active_support/ordered_hash.rb | 8 ++++++++ activesupport/test/ordered_hash_test.rb | 9 +++++++++ 2 files changed, 17 insertions(+), 0 deletions(-) diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index 66aab9e..72307a6 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -95,6 +95,14 @@ module ActiveSupport def inspect "#" end + + def to_json(options = {}) + "{" + self.map { |i,j| "\"#{i}\": #{ActiveSupport::JSON.encode(j, options)}" }.join(", ") + "}" + end + + def to_xml(options = {}) + self.map { |i,j| "<#{i}>#{j}" } + end private diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index fb76ca1..8e30292 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -148,4 +148,13 @@ class OrderedHashTest < Test::Unit::TestCase @ordered_hash.keys.pop assert_equal original, @ordered_hash.keys end + + def test_to_json + json_hash = @ordered_hash.to_json + assert_equal json_hash, '{"blue": "000099", "green": "009900", "red": "aa0000", "pink": "cc0066", "orange": "cc6633"}' + end + def test_to_xml + xml_hash = @ordered_hash.to_xml + assert_equal xml_hash, '000099009900aa0000cc0066cc6633' + end end \ No newline at end of file -- 1.6.1