Skip to content

Instantly share code, notes, and snippets.

@MichalBryxi
Last active December 16, 2015 02:19
Show Gist options
  • Save MichalBryxi/5361543 to your computer and use it in GitHub Desktop.
Save MichalBryxi/5361543 to your computer and use it in GitHub Desktop.
In ruby 1.8 you don't have option to serialize hashes sorted. You can find many monkey patches on the internet which allows this. Unfortunatelly there are numerous errors in them. I would like to keep here most bug-free version.
class Hash # :nodoc:
undef_method :to_yaml
# Replacing the to_yaml function so it'll serialize hashes sorted (by their keys)
#
# Original function is in /usr/lib/ruby/1.8/yaml/rubytypes.rb
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.map( taguri, to_yaml_style ) do |map|
keys.sort_by do |k|
k.to_s
end.each do |k|
map.add( k.to_s, fetch(k) )
end
end
end
end
end
@MichalBryxi
Copy link
Author

Revision #2 fixes problem with:

#<TypeError: wrong argument type Fixnum (expected String)>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment