Skip to content

Instantly share code, notes, and snippets.

@aulizko
Created December 20, 2010 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aulizko/749048 to your computer and use it in GitHub Desktop.
Save aulizko/749048 to your computer and use it in GitHub Desktop.
Overrides content of the en.yml file with content of ru.yml. Unique entries for en.yml remains untouched.
require 'rubygems'
require 'yaml'
require 'ya2yaml'
$KCODE = 'u'
class Hash
def deep_stringify_keys
new_hash = {}
self.each do |key, value|
new_hash.merge!(key.to_s => (value.is_a?(Hash) ? value.deep_stringify_keys : value))
end
end
end
ru = YAML::load(File.open('ru.yml'))
en = YAML::load(File.open('en.yml'))
def build_access_string(arr)
result = ""
arr.each do |entry|
result << "["
if entry.is_a? String
result << "\"" + entry + "\""
else
result << entry.to_s
end
result << "]"
end
result
end
def write_to_en_hash(sc, path, value)
path.shift
path.unshift("en")
for i in 0..(path.length - 1) do
access_string = build_access_string(path[0..i])
old_value = eval("en" + access_string, sc)
if (old_value.nil?)
if (i == (path.length - 1))
if (value.is_a? String)
eval("en" + access_string + "=" + "\"" + value.gsub("\"", "\\\"") + "\"", sc)
else
eval("en" + access_string + "=" + value.to_s, sc)
end
else
eval("en" + access_string + "= Hash.new", sc)
end
elsif (!old_value.is_a?(Hash) && (i != (path.length - 1)))
eval("en" + access_string + "= Hash.new", sc)
elsif (i == (path.length - 1))
if (value.is_a? String)
eval("en" + access_string + "=" + "\"" + value.gsub("\"", "\\\"").gsub("#", "\\#") + "\"", sc)
else
eval("en" + access_string + "=" + value.to_s, sc)
end
end
end
end
def traverse(sc, obj, path)
case obj
when Hash
obj.each do |k,v|
traverse(sc, v, path + [k])
end
when Array
obj.each {|v| traverse(sc, v) }
else # end values
write_to_en_hash(sc, path, obj)
end
end
def write(filename, hash)
File.open(filename, "w") do |f|
f.write(yaml(hash))
end
end
def yaml(hash)
method = hash.respond_to?(:ya2yaml) ? :ya2yaml : :to_yaml
string = hash.deep_stringify_keys.send(method)
string.gsub("!ruby/symbol ", ":").sub("---","").split("\n").map(&:rstrip).join("\n").strip
end
traverse(binding, ru, [])
write("result.yml", en)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment