Skip to content

Instantly share code, notes, and snippets.

@AquaGeek
Created May 14, 2011 02:09
Show Gist options
  • Save AquaGeek/971609 to your computer and use it in GitHub Desktop.
Save AquaGeek/971609 to your computer and use it in GitHub Desktop.
Rails Lighthouse ticket #1895
From 8d1f611225e72139cdc0615fcb79cdb4fb88f234 Mon Sep 17 00:00:00 2001
From: Damien MATHIEU <dmathieu@dmathieu.local>
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
"#<OrderedHash #{self.to_hash.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}</#{i}>" }
+ 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, '<blue>000099</blue><green>009900</green><red>aa0000</red><pink>cc0066</pink><orange>cc6633</orange>'
+ end
end
\ No newline at end of file
--
1.6.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment