Skip to content

Instantly share code, notes, and snippets.

@niedhui
Last active October 10, 2016 06:07
Show Gist options
  • Save niedhui/87b341fd17e9bfdfbbe2aa8ca69bd0eb to your computer and use it in GitHub Desktop.
Save niedhui/87b341fd17e9bfdfbbe2aa8ca69bd0eb to your computer and use it in GitHub Desktop.
require 'i18n'
require 'dry-validation'
require 'dry/validation/version'
puts "dry-validation version: #{Dry::Validation::VERSION}"
puts "\n\n#{'#' * 20} \n\n"
I18n.backend.store_translations(:'zh-CN', {errors: {str?: '必须是字符串'}})
schema = Dry::Validation.Schema do
configure {
config.messages = :i18n
}
required(:email).filled(:str?)
end
def show_message(schema)
puts "I18n.locale is #{I18n.locale}"
result = schema.(email: 122)
puts "result messages: #{result.messages}"
puts "result messages(explicit locale) #{result.messages(locale: I18n.locale)}"
puts "I18n.t: #{I18n.t("errors.str?")}"
puts "#{result.messages[:email].first == I18n.t('errors.str?') }"
end
show_message(schema)
puts "\n\n#{'#' * 20} \n\n"
I18n.locale = :'zh-CN'
show_message(schema)
require 'rspec'
require 'i18n'
require 'dry-validation'
require 'dry/validation/version'
context "I18n Message" do
before do
I18n.backend.store_translations(:'zh-CN', {errors: {str?: '必须是字符串'}})
end
let!(:schema) do
schema = Dry::Validation.Schema do
configure {
config.messages = :i18n
}
required(:email).filled(:str?)
end
end
context "en(default) locale" do
it do
expect_message = 'must be a string'
result = schema.(email: 122)
result_message = result.messages[:email].first
result_message_explict_locale = result.messages(locale: I18n.locale)[:email].first
i18n_message = I18n.t("errors.str?")
expect(result_message).to eq(expect_message)
expect(result_message).to eq(result_message_explict_locale)
expect(result_message).to eq(i18n_message)
end
end
context "zh-CN locale" do
it do
I18n.locale = :'zh-CN'
expect_message = '必须是字符串'
result = schema.(email: 122)
result_message = result.messages[:email].first
result_message_explict_locale = result.messages(locale: I18n.locale)[:email].first
i18n_message = I18n.t("errors.str?")
expect(i18n_message).to eq(expect_message) # pass
expect(result_message_explict_locale).to eq(expect_message) # pass
expect(result_message).to eq(expect_message) # fail
expect(result_message).to eq(i18n_message) # fail
end
end
end
@niedhui
Copy link
Author

niedhui commented Oct 10, 2016

the console output

dry-validation version: 0.10.3


####################

I18n.locale is en
result messages: {:email=>["must be a string"]}
result messages(explicit locale) {:email=>["must be a string"]}
I18n.t: must be a string
true


####################

I18n.locale is zh-CN
result messages: {:email=>["must be a string"]}
result messages(explicit locale) {:email=>["必须是字符串"]}
I18n.t: 必须是字符串
false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment