Created
January 23, 2019 16:34
-
-
Save abratashov/2d7f9805d306083c817e55674f5a83cc to your computer and use it in GitHub Desktop.
This file contains 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
gem 'deep_merge' |
This file contains 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
'en.pets.types.cat': Cat | |
'en.pets.types.dog': Dog | |
'en.pets.title': My lovely pets | |
'en.actions.add': Add | |
'en.actions.remove': Remove | |
'en.language': <strong>Language</strong> |
This file contains 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
--- | |
en: | |
pets: | |
types: | |
cat: Cat | |
dog: Dog | |
title: My lovely pets | |
actions: | |
add: Add | |
remove: Remove | |
language: "<strong>Language</strong>" |
This file contains 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
require 'yaml' | |
require 'deep_merge' | |
require 'fileutils' | |
class YAMLConverter | |
def initialize(filepath) | |
@filepath = filepath | |
@filepath_converted = "#{@filepath.split('.')[0..-2].join}_converted.yml" | |
end | |
def generate | |
File.open(@filepath_converted, 'w') {|f| f.write converted } | |
end | |
def converted | |
hash = {} | |
YAML::load_file(@filepath).each do |key, value| | |
new_hash = create_hash(key.split('.'), value) | |
hash.deep_merge!(new_hash) | |
end | |
hash.to_yaml | |
end | |
private | |
def create_hash(keys, value) | |
hash = { "#{keys[-1]}" => value } | |
keys.reverse[1..-1].each do |subkey| | |
hash = { "#{subkey}" => hash } | |
end | |
hash | |
end | |
end | |
class YAMLConverterTest | |
class << self | |
def passed? | |
match('translations_simple_test.yml', 'translations_simple_test_converted.yml') | |
end | |
private | |
def match(test_yml, expected_yml) | |
YAMLConverter.new("#{Dir.pwd}/#{test_yml}").generate | |
puts File.read("#{Dir.pwd}/translations_simple_test_converted.yml") | |
puts '' | |
result = FileUtils.compare_file('translations_simple_test_converted.yml', 'translations_simple_test_expected.yml') | |
FileUtils.rm_f("#{Dir.pwd}/translations_simple_test_converted.yml") | |
result | |
end | |
end | |
end | |
puts (YAMLConverterTest.passed? ? 'Tests passed successfully' : 'Tests passed with failure') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment