Browse files

Adding custom yaml (de-)serialization for OrderedHash

[#3608 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information...
1 parent 652bdeb commit 57337cd74db0596a1e9f8eb0e6df0bb8ccf53dd2 @schmidt schmidt committed with jeremy Jan 26, 2010
View
10 activesupport/CHANGELOG
@@ -1,4 +1,10 @@
-*Edge*
+*2.3.6 (pending)*
+
+* YAML serialization for OrderedHash. #3608 [Gregor Schmidt]
+
+* Update bundled TZInfo to v0.3.16 [Geoff Buesing]
+
+* Georgetown TimeZone is now mapped to "America/Guyana" instead of "America/Argentina/San_Juan" #1821 [Geoff Buesing, Reuben Sivan]
* Add Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?/else calls [DHH]
@@ -13,12 +19,14 @@
* Ruby 1.9 Compatibility
+
*2.3.4 (September 4, 2009)*
* Introduce ActiveSupport::Multibyte.clean to clean invalid multibyte strings.
* Bug fixes
+
*2.3.3 (July 12, 2009)*
* JSON: +Object#to_json+ calls +as_json+ to coerce itself into something natively encodable like +Hash+, +Integer+, or +String+. Override +as_json+ instead of +to_json+ so you're JSON-library-agnostic. [Jeremy Kemper]
View
23 activesupport/lib/active_support/ordered_hash.rb
@@ -2,7 +2,8 @@
module ActiveSupport
# Hash is ordered in Ruby 1.9!
if RUBY_VERSION >= '1.9'
- OrderedHash = ::Hash
+ class OrderedHash < ::Hash #:nodoc:
+ end
else
class OrderedHash < Hash #:nodoc:
def initialize(*args, &block)
@@ -138,4 +139,24 @@ def sync_keys!
end
end
end
+
+ class OrderedHash #:nodoc:
+ def to_yaml_type
+ "!tag:yaml.org,2002:omap"
+ end
+
+ def to_yaml(opts = {})
+ YAML.quick_emit(self, opts) do |out|
+ out.seq(taguri, to_yaml_style) do |seq|
+ each do |k, v|
+ seq.add(k => v)
+ end
+ end
+ end
+ end
+ end
+
+ YAML.add_builtin_type("omap") do |type, val|
+ ActiveSupport::OrderedHash[val.map(&:to_a).map(&:first)]
+ end
end
View
24 activesupport/test/ordered_hash_test.rb
@@ -198,4 +198,28 @@ def test_replace_updates_keys
assert_same original, @ordered_hash
assert_equal @other_ordered_hash.keys, @ordered_hash.keys
end
+
+ def test_each_after_yaml_serialization
+ values = []
+ @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+
+ @deserialized_ordered_hash.each {|key, value| values << value}
+ assert_equal @values, values
+ end
+
+ def test_order_after_yaml_serialization
+ @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+
+ assert_equal @keys, @deserialized_ordered_hash.keys
+ assert_equal @values, @deserialized_ordered_hash.values
+ end
+
+ def test_order_after_yaml_serialization_with_nested_arrays
+ @ordered_hash[:array] = %w(a b c)
+
+ @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+
+ assert_equal @ordered_hash.keys, @deserialized_ordered_hash.keys
+ assert_equal @ordered_hash.values, @deserialized_ordered_hash.values
+ end
end

0 comments on commit 57337cd

Please sign in to comment.