2010-01-27 20:03:05 -05:00
|
|
|
require 'yaml'
|
|
|
|
|
2010-04-09 22:33:42 -04:00
|
|
|
YAML.add_builtin_type("omap") do |type, val|
|
2011-07-23 16:21:39 -04:00
|
|
|
ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }]
|
2010-04-09 22:33:42 -04:00
|
|
|
end
|
|
|
|
|
2008-05-14 13:48:37 -04:00
|
|
|
module ActiveSupport
|
2012-05-16 15:44:57 -04:00
|
|
|
# <tt>ActiveSupport::OrderedHash</tt> implements a hash that preserves
|
|
|
|
# insertion order.
|
2010-08-14 01:13:00 -04:00
|
|
|
#
|
2010-08-06 07:11:44 -04:00
|
|
|
# oh = ActiveSupport::OrderedHash.new
|
|
|
|
# oh[:a] = 1
|
|
|
|
# oh[:b] = 2
|
|
|
|
# oh.keys # => [:a, :b], this order is guaranteed
|
2010-08-14 01:13:00 -04:00
|
|
|
#
|
2012-05-16 15:44:57 -04:00
|
|
|
# Also, maps the +omap+ feature for YAML files
|
|
|
|
# (See http://yaml.org/type/omap.html) to support ordered items
|
|
|
|
# when loading from yaml.
|
|
|
|
#
|
|
|
|
# <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts
|
|
|
|
# with other implementations.
|
2011-11-22 06:42:37 -05:00
|
|
|
class OrderedHash < ::Hash
|
2010-04-09 22:33:42 -04:00
|
|
|
def to_yaml_type
|
|
|
|
"!tag:yaml.org,2002:omap"
|
2010-01-26 06:02:31 -05:00
|
|
|
end
|
2010-04-09 22:33:42 -04:00
|
|
|
|
2011-01-04 17:09:35 -05:00
|
|
|
def encode_with(coder)
|
|
|
|
coder.represent_seq '!omap', map { |k,v| { k => v } }
|
|
|
|
end
|
|
|
|
|
2011-05-08 05:21:06 -04:00
|
|
|
def nested_under_indifferent_access
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2011-09-03 03:43:33 -04:00
|
|
|
# Returns true to make sure that this hash is extractable via <tt>Array#extract_options!</tt>
|
|
|
|
def extractable_options?
|
|
|
|
true
|
|
|
|
end
|
2010-01-26 06:02:31 -05:00
|
|
|
end
|
2008-05-14 13:48:37 -04:00
|
|
|
end
|