2008-12-17 16:49:06 +00:00
|
|
|
# --
|
2009-01-06 15:51:01 +00:00
|
|
|
# Copyright (C) 2008-2009 10gen Inc.
|
2008-12-17 16:43:08 +00:00
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
|
|
# under the terms of the GNU Affero General Public License, version 3, as
|
|
|
|
# published by the Free Software Foundation.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
|
|
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
|
|
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
|
|
|
|
# for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
2008-12-17 16:49:06 +00:00
|
|
|
# ++
|
2008-12-17 16:43:08 +00:00
|
|
|
|
|
|
|
# A hash in which the order of keys are preserved.
|
2008-12-08 16:38:42 +00:00
|
|
|
class OrderedHash < Hash
|
|
|
|
|
|
|
|
attr_accessor :ordered_keys
|
|
|
|
|
|
|
|
def keys
|
|
|
|
@ordered_keys || []
|
|
|
|
end
|
|
|
|
|
|
|
|
def []=(key, value)
|
|
|
|
@ordered_keys ||= []
|
|
|
|
@ordered_keys << key unless @ordered_keys.include?(key)
|
|
|
|
super(key, value)
|
|
|
|
end
|
|
|
|
|
|
|
|
def each
|
|
|
|
@ordered_keys ||= []
|
|
|
|
@ordered_keys.each { |k| yield k, self[k] }
|
|
|
|
end
|
|
|
|
|
2009-01-08 12:16:25 +00:00
|
|
|
def values
|
|
|
|
collect { |k, v| v }
|
|
|
|
end
|
|
|
|
|
2008-12-08 16:38:42 +00:00
|
|
|
def merge(other)
|
2009-01-08 12:16:25 +00:00
|
|
|
oh = self.dup
|
|
|
|
oh.merge!(other)
|
|
|
|
oh
|
|
|
|
end
|
|
|
|
|
|
|
|
def merge!(other)
|
2008-12-08 16:38:42 +00:00
|
|
|
@ordered_keys ||= []
|
|
|
|
@ordered_keys += other.keys # unordered if not an OrderedHash
|
2009-01-08 12:16:25 +00:00
|
|
|
@ordered_keys.uniq!
|
2008-12-08 16:38:42 +00:00
|
|
|
super(other)
|
|
|
|
end
|
|
|
|
|
2009-01-09 18:54:12 +00:00
|
|
|
def inspect
|
|
|
|
str = '{'
|
|
|
|
str << @ordered_keys.collect { |k| "\"#{k}\"=>#{self.[](k).inspect}" }.join(", ")
|
|
|
|
str << '}'
|
|
|
|
end
|
|
|
|
|
2008-12-08 16:38:42 +00:00
|
|
|
end
|