Skip to content

Instantly share code, notes, and snippets.

@aalin
Created March 22, 2012 17:04
Show Gist options
  • Select an option

  • Save aalin/2159750 to your computer and use it in GitHub Desktop.

Select an option

Save aalin/2159750 to your computer and use it in GitHub Desktop.
Rails locale formatter
#!/usr/bin/env ruby
# encoding: utf-8
require 'yaml'
require 'stringio'
class LocaleFormatter
ESCAPE_KEYS = %w(true false yes no on off)
ESCAPE_VALUE_RE = /[^[:alnum:]_\-\/\.\?]/
MULTILINE_INDENT_LEVEL = 2
def initialize(yaml)
@locale = YAML.load(yaml)
end
def to_s
stream = StringIO.new
stream.puts "---"
print_locale(stream, @locale)
stream.rewind
stream.read
end
private
def print_locale(stream, tree, level = 0)
tree.sort_by { |k, v| k }.each do |key, values|
if values.is_a?(Hash)
stream.puts indent("#{ escape_key(key) }:", level)
print_locale(stream, values, level.next)
elsif values.include?("\n")
stream.puts indent("#{ escape_key(key) }: |", level)
stream.puts indent(values, level + MULTILINE_INDENT_LEVEL)
elsif values.match(ESCAPE_VALUE_RE)
stream.puts indent("#{ escape_key(key) }: #{ values.inspect }", level)
else
stream.puts indent("#{ escape_key(key) }: #{ values }", level)
end
end
end
def indent(str, level)
str.gsub(/^/, " " * level)
end
def escape_key(key)
if ESCAPE_KEYS.include?(key)
"\"#{ key }\""
else
key
end
end
end
puts LocaleFormatter.new(ARGF.read)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment