Skip to content

Instantly share code, notes, and snippets.

@sawanoboly
Created April 19, 2015 05:10
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 sawanoboly/e0e269c439c53fe33352 to your computer and use it in GitHub Desktop.
Save sawanoboly/e0e269c439c53fe33352 to your computer and use it in GitHub Desktop.
普通なRubyプログラムでもi18nで多言語対応してみる ref: http://qiita.com/sawanoboly/items/b1c16814ec6f08503290
#!/usr/bin/env ruby
# coding: utf-8
require 'i18n'
require 'yaml'
I18n.enforce_available_locales = true ## 対応ずみ言語かを実行時にチェックして止める
I18n.backend = I18n::Backend::Simple.new
## Yamlのパスをアレイで渡すとロードする
I18n.backend.load_translations(Dir.glob('locales/*.yml'))
## backend.translateにロケールとキーを渡すパターン
%w[en ja].map do |lang|
puts I18n.backend.translate lang.to_sym, :of
end
## I18n.tにオプションでロケールを渡すパターン
I18n.backend.available_locales.map do |lang|
puts I18n.t :by, {locale: lang.to_sym}
end
## I18n.tのオプションを省略するパターン
%w[en ja].map do |lang|
I18n.locale = lang.to_sym
puts I18n.t :for
end
#!/usr/bin/env ruby
# coding: utf-8
require 'i18n'
require 'yaml'
I18n.enforce_available_locales = false # 未対応言語でも止めない
I18n.backend = I18n::Backend::Simple.new
## デフォルト言語にフォールバック https://github.com/svenfuchs/i18n/wiki/Fallbacks
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
I18n.backend.load_translations(Dir.glob('locales/*.yml'))
%w[en ja].map do |lang|
puts I18n.backend.translate lang.to_sym, :of
end
I18n.backend.available_locales.map do |lang|
puts I18n.t :by, {locale: lang.to_sym}
end
I18n.default_locale = :en # デフォルトでも:en
%w[en ja de].map do |lang|
I18n.locale = lang.to_sym
puts I18n.translate :for
end
---
en:
of: of the people
by: by the people
for: for the people
$ bundle exec ruby app.rb
of the people
人民の
by the people
人民による
for the people
人民のための
$ bundle exec ruby app.rb
of the people
人民の
by the people
人民による
for the people
for the people
$ bundle exec ruby app.rb
of the people
人民の
by the people
人民による
for the people
for the people
for the people
---
ja:
of: 人民の
by: 人民による
# for: 人民のための
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment