Created
May 16, 2014 04:08
-
-
Save matismasters/a835e86c99143303a5b0 to your computer and use it in GitHub Desktop.
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
require 'yaml' | |
# For some weird reason I ended up creating a script to create specs | |
# for testing the I18n Locale file. It happens that I never used it anyway | |
# but it might be of use to someone so I'll leave it here. | |
# | |
# This assumes you use I18n, and also uses the YAML gem. The example is | |
# default configured for the Rails path to the locale file, but off course | |
# you can change it. | |
# | |
# Note: This is just a generator in case you already started your project | |
# without testing your I18n files. So for special cases where you have | |
# interpolation, go ahead and fix it manually | |
class I18nSpecGenerator | |
def initialize(localization_file_path) | |
@keys = [] | |
@final_keys = [] | |
@yaml_file = YAML.load_file(localization_file_path) | |
end | |
def generate_specs | |
@yaml_file.each do |key, value| | |
build_string(key, value) | |
end | |
end | |
def print_specs_to_file(file_name) | |
output_file = File.new(file_name, 'w') | |
output_file.write("require 'spec_helper'\n") | |
output_file.write("\n") | |
output_file.write("# This file contains one test per I18n key\n") | |
output_file.write("\n") | |
generate_specs if @final_keys.empty? | |
@final_keys.each do |key_value_pair| | |
output_file.write("it { expect(I18n.t('#{key_value_pair[:key]}').to " + | |
"eq(\"#{key_value_pair[:value]}\") }\n") | |
end | |
output_file.close | |
end | |
def build_string(key, value) | |
@keys << key | |
if value.is_a?(Hash) | |
value.each do |inner_key, inner_value| | |
build_string(inner_key, inner_value) | |
end | |
@keys = [] | |
else | |
@final_keys << { key: @keys.join('.'), value: value } | |
end | |
end | |
end | |
generator = I18nSpecGenerator.new('./config/locales/en.yml') | |
generator.print_specs_to_file('i18n_spec.rb') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment