Created
April 7, 2010 09:52
-
-
Save akm/358709 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# HashKeyOrderable | |
# sort key and values for your order. MIT LICENCE. copyright Takeshi AKIMA 2010. | |
# http://gist.github.com/358709 | |
module HashKeyOrderable | |
attr_accessor :key_order | |
def each_with_key_order(&block) | |
if @key_order.nil? || @key_order.empty? | |
each_without_key_order(&block) | |
return self | |
end | |
unexist_keys = @key_order - self.keys | |
actual_order = (@key_order - unexist_keys) | self.keys | |
actual_order.each do |key| | |
yield(key, self[key]) | |
end | |
self | |
end | |
def inspect | |
result = [] | |
each_with_key_order do |key, value| | |
result << "#{key.inspect}=>#{value.inspect}" | |
end | |
'{%s}' % result.join(', ') | |
end | |
def self.extended(obj) | |
obj.instance_eval do | |
alias :each_without_key_order :each | |
alias :each :each_with_key_order | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment