Skip to content

Instantly share code, notes, and snippets.

@mcallaway
Last active August 29, 2015 14:07
Show Gist options
  • Save mcallaway/356b72e8cae8abde0508 to your computer and use it in GitHub Desktop.
Save mcallaway/356b72e8cae8abde0508 to your computer and use it in GitHub Desktop.
Modifying to_yaml for hash
class Hash
# 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|
sort.each do |k, v| # <-- here's my addition (the 'sort')
map.add( k, v )
end
end
end
end
end
# Direct use in a template doesn't work:
<%=
class Hash
# 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|
sort.each do |k, v| # <-- here's my addition (the 'sort')
map.add( k, v )
end
end
end
end
end
scope.to_hash.reject{ |k,v| k.to_s =~ /(uptime_seconds|timestamp|free)/ }.to_yaml
%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment