Created
March 22, 2012 17:04
-
-
Save aalin/2159750 to your computer and use it in GitHub Desktop.
Rails locale formatter
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
| #!/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