- 浏览: 2542535 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Rails Study(12)I18N Overview
1 How I18n in Ruby on Rails Works
Internationalization is a complex problem.
1.1 The Overall Architecture of the Library
The ruby I18n gem is split into two parts:
* The public API of the i18n framework
* A default backend
1.2 The Public I18n API
The most important methods of the I18n API: translate, localize
I18n.t 'store.title'
I18n.l Time.now
load_path # announce your custom translation files
locale # get and set the current locale
default_locale # get and set the default locale
exeption_hander
backend
2 Setup the Rails Application for Internationalization
2.1 Configure the I18n Module
Rails adds all *.rb and *.yml files from the config/locales directory to your translations load path.
The configuration file config/application.rb can configure this.
2.2 Optional: Custom I18n Configuration Setup
Put the configuration in one initializer:
#in config/initializers/locale.rb
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
I18n.default_locale = :pt
2.3 Setting and Passing the Locale
If you want to provide support for more locales in your application, you need to set and pass the locale between requests.
Notices: Do not store the chosen locale in a session or a cookie. The locale should be transparent and a part of the URL. This way you do not break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content.
In ApplicationController before_filter:
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
We need to pass the locale as a URL query parameter
http://example.com/books?locale=pt
http://localhost:3000?locale=pt
2.4 Setting the Locale from the Domain Name
For example, we want www.example.com to load the English (or default) locale, and www.example.es to load the Spanish locale.
We can implement it like this in ApplicationController
before_filter :set_locale
def set_locale
I18n.locale = extract_locale_from_tld || I18n.default_locale
end
#get locale from top-level domain
def extract_local_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale
end
to_sym converts a string to a symbol. For example, "a".to_sym becomes :a
or set the locale from the subdomain
def extract_locale_from_subdomain
parsed_locale = request.subdomains.first
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale
end
2.5 Setting the Locale from the URL Params
to get the URL like this
http://www.example.com/books?locale=ja
link_to( books_url(:locale => I18n.locale))
And we can deal with this in ApplicationController#default_url_options
#app/controllers/application_controller.rb
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{:locale => I18n.locale}
end
Every helper method dependent on url_for (e.g. root_path, root_url, books_path, books_url and etc.) will now automatically include the locale in the query string.
to get this kind of URL http://www.example.com/en/books
set up your routes with path_prefix option in this way:
#config/routes.rb
scope "/:locale" do
resources :books
end
To make that there is default URL and some special URL
#config/routes.rb
scope "(:locale)", :locale => /en|nl/ do
resources :books
end
And take care of the root path
#config/routes.rb
match '/:locale' => 'dashboard#index'
2.6 Setting the Locale from the Client Supplied Information
It would make sense to set the locale from client-supplied information, for example, from the users' preferred language (set in their browser).
2.6.1 Using Accept-Language
One source of client supplied information would be an Accept-Language HTTP header.
def set_locale
logger.debug "*Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
I18n.locale = extract_locale_from_accept_language_header
logger.debug "* Locale set to '#{I18n.locale}'"
end
private
def extract_locale_from_accept_language_header
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
scan/^[a-z]{2}/ is the regex statement.
2.6.2 Using GeoIP(or Similar) Database
2.6.3 User Profile
3. Internationalizing your Application
home page controller class
class HomeController < ApplicationController
def index
flash[:notice] = "Hello master!"
end
end
erb html files
<p><%= flash[:notice] %></p>
3.1 Adding Translations
To internationalize this code, replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:
app/controllers/application_controller.rb
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{:locale => I18n.locale}
end
home_controller.rb
def index
#flash[:notice] = "Hello master!"
flash[:notice] = t(:hello_flash)
end
erb file index.html.erb
<p><%=t :hello_world %></p>
<p><%= flash[:notice] %></p>
yml file config/locales/en.yml
en:
hello_flash: Hello God
hello_world: hello Hell
test:
hello_flash: test God
hello_world: test Hell
Actually, we can also make en.yml into 2 files en.yml and test.yml.
With the visited URL http://localhost:3000/
hello Hell
Hello God
With the visited URL http://localhost:3000/?locale=test
test Hell
test God
3.2 Adding Date/Time Formats
We can pass the Time object to I18n.l or use Rails' #l helper. You can pick a format by passing the :format option, :default for default format.
erb html file
<p><%= l Time.now, :format => :short %></p>
in the yml file
en:
time:
formats:
short: "time %H %m %s"
test:
time:
formats:
short: "time %H"
3.3 Localized Views
Rails 2.3 introduces another convenient localization feature: localized views (templates).
app/views/books/index.html.erb, but if locale is :es, it will render to index.es.html.erb.
I add a file index.cn.html.erb in the same directory with content hello Chinese! And when I access the URL
http://localhost:3000/?locale=cn, I got the content in index.cn.html.erb
3.4 Organization of Locale Files
references:
http://guides.rubyonrails.org/i18n.html
http://www.yotabanana.com/hiki/ruby-gettext-howto-rails.html
http://ruby-i18n.org/wiki
http://st-on-it.blogspot.com/2008/07/rails-gettext-crashcourse.html
https://github.com/mutoh/gettext_rails
sample URL
https://github.com/mutoh/gettext_rails/blob/master/sample/config/environment.rb
1 How I18n in Ruby on Rails Works
Internationalization is a complex problem.
1.1 The Overall Architecture of the Library
The ruby I18n gem is split into two parts:
* The public API of the i18n framework
* A default backend
1.2 The Public I18n API
The most important methods of the I18n API: translate, localize
I18n.t 'store.title'
I18n.l Time.now
load_path # announce your custom translation files
locale # get and set the current locale
default_locale # get and set the default locale
exeption_hander
backend
2 Setup the Rails Application for Internationalization
2.1 Configure the I18n Module
Rails adds all *.rb and *.yml files from the config/locales directory to your translations load path.
The configuration file config/application.rb can configure this.
2.2 Optional: Custom I18n Configuration Setup
Put the configuration in one initializer:
#in config/initializers/locale.rb
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
I18n.default_locale = :pt
2.3 Setting and Passing the Locale
If you want to provide support for more locales in your application, you need to set and pass the locale between requests.
Notices: Do not store the chosen locale in a session or a cookie. The locale should be transparent and a part of the URL. This way you do not break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content.
In ApplicationController before_filter:
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
We need to pass the locale as a URL query parameter
http://example.com/books?locale=pt
http://localhost:3000?locale=pt
2.4 Setting the Locale from the Domain Name
For example, we want www.example.com to load the English (or default) locale, and www.example.es to load the Spanish locale.
We can implement it like this in ApplicationController
before_filter :set_locale
def set_locale
I18n.locale = extract_locale_from_tld || I18n.default_locale
end
#get locale from top-level domain
def extract_local_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale
end
to_sym converts a string to a symbol. For example, "a".to_sym becomes :a
or set the locale from the subdomain
def extract_locale_from_subdomain
parsed_locale = request.subdomains.first
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale
end
2.5 Setting the Locale from the URL Params
to get the URL like this
http://www.example.com/books?locale=ja
link_to( books_url(:locale => I18n.locale))
And we can deal with this in ApplicationController#default_url_options
#app/controllers/application_controller.rb
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{:locale => I18n.locale}
end
Every helper method dependent on url_for (e.g. root_path, root_url, books_path, books_url and etc.) will now automatically include the locale in the query string.
to get this kind of URL http://www.example.com/en/books
set up your routes with path_prefix option in this way:
#config/routes.rb
scope "/:locale" do
resources :books
end
To make that there is default URL and some special URL
#config/routes.rb
scope "(:locale)", :locale => /en|nl/ do
resources :books
end
And take care of the root path
#config/routes.rb
match '/:locale' => 'dashboard#index'
2.6 Setting the Locale from the Client Supplied Information
It would make sense to set the locale from client-supplied information, for example, from the users' preferred language (set in their browser).
2.6.1 Using Accept-Language
One source of client supplied information would be an Accept-Language HTTP header.
def set_locale
logger.debug "*Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
I18n.locale = extract_locale_from_accept_language_header
logger.debug "* Locale set to '#{I18n.locale}'"
end
private
def extract_locale_from_accept_language_header
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
scan/^[a-z]{2}/ is the regex statement.
2.6.2 Using GeoIP(or Similar) Database
2.6.3 User Profile
3. Internationalizing your Application
home page controller class
class HomeController < ApplicationController
def index
flash[:notice] = "Hello master!"
end
end
erb html files
<p><%= flash[:notice] %></p>
3.1 Adding Translations
To internationalize this code, replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:
app/controllers/application_controller.rb
before_filter :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{:locale => I18n.locale}
end
home_controller.rb
def index
#flash[:notice] = "Hello master!"
flash[:notice] = t(:hello_flash)
end
erb file index.html.erb
<p><%=t :hello_world %></p>
<p><%= flash[:notice] %></p>
yml file config/locales/en.yml
en:
hello_flash: Hello God
hello_world: hello Hell
test:
hello_flash: test God
hello_world: test Hell
Actually, we can also make en.yml into 2 files en.yml and test.yml.
With the visited URL http://localhost:3000/
hello Hell
Hello God
With the visited URL http://localhost:3000/?locale=test
test Hell
test God
3.2 Adding Date/Time Formats
We can pass the Time object to I18n.l or use Rails' #l helper. You can pick a format by passing the :format option, :default for default format.
erb html file
<p><%= l Time.now, :format => :short %></p>
in the yml file
en:
time:
formats:
short: "time %H %m %s"
test:
time:
formats:
short: "time %H"
3.3 Localized Views
Rails 2.3 introduces another convenient localization feature: localized views (templates).
app/views/books/index.html.erb, but if locale is :es, it will render to index.es.html.erb.
I add a file index.cn.html.erb in the same directory with content hello Chinese! And when I access the URL
http://localhost:3000/?locale=cn, I got the content in index.cn.html.erb
3.4 Organization of Locale Files
references:
http://guides.rubyonrails.org/i18n.html
http://www.yotabanana.com/hiki/ruby-gettext-howto-rails.html
http://ruby-i18n.org/wiki
http://st-on-it.blogspot.com/2008/07/rails-gettext-crashcourse.html
https://github.com/mutoh/gettext_rails
sample URL
https://github.com/mutoh/gettext_rails/blob/master/sample/config/environment.rb
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 468NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 330Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 377Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 468NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 414Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 332Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 243GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 445GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 321GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 307Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 286Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 303Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 282NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 257Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 565NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 257Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 362Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 366Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
rails-i18n, 用于收集 Ruby on Rails i18n 环境数据以及其他有趣的Rails 相关 i18n 内容的存储库 Rails 语言环境数据存储库 中心收集区域设置数据,以便在 ruby 上使用。 gem-安装添加到你的Gemfile:gem 'rails-i18n...
mail_form, 在 Rails 中使用 i18n 验证附件和请求信息,直接从表单发送电子邮件 MailForm Rails 3这个 gem 构建在 ActiveModel 之上,展示如何从 Rails 中提取验证。命名和 i18n,而不需要自己实现。本自述文件指的...
i18n...# You *must* choose GetText or Rails-i18n style checking# If you want GetText-style checkingI18n/GetText: Enabled: trueI18n/RailsI18n: Enabled: false# If you want rails-i18n
适用于JavaScript的Ruby on Rails i18n 该gem通过Rack中间件公开您的JSON序列化翻译,以便将它们与JavaScript结合使用。 安装 此宝石正在开发中,这些步骤可能会更改 # Gemfile gem 'rails-i18n-js', :git => '...
react-i18n 该模块与 gem集成在一起,并作为的包装器构建。 基本设定 安装模块 $ npm install --save i18n-js react-i18n 设置i18n-js 在Gemfile中 gem 'i18n-js' 您认为* .haml :javascript I18n.default...
I18nTimezones I18n时区-此gem的目的是简单地提供时区转换。 该gem易于与需要i18n时区转换的其他gem结合使用,因此我们可以使用通用的i18n时区转换gem。 如果您要对时区和翻译做任何事情,则无需重新发明轮子并...
百济I18n 这是一个小库,可以在JavaScript上提供Rails I18n的翻译。 从借来的特征: 多元化日期/时间本地化号码本地化语言环境回退资产管道支持还有更多! :)用法安装通过NPM npm install baiji-i18n 运行npm ...
I18nLinter ...只需在Ruby on Rails项目的文件夹中输入i18n_linter ,然后观察可以国际化的字符串即可。 注意:仅报告ruby文件中的字符串。 $ cd my/ruby_on_rails/project $ i18n_linter [options]
模仿Rails的i18n界面。用法const I18n = require ( '@fiverr/i18n' ) ;const translations = require ( './translations.json' ) ;const i18n = new I18n ( { translations } ) ; 选项类型描述translations 目的...
I18nRouting I18n_routing是Ruby on Rails的插件,可让您轻松地通过版本2.2以后的Rails中包含的I18n api转换路线。 所有必需的信息都可以在Wiki上找到: 如有疑问,请使用i18_routing谷歌论坛: 适用于Rails 2.3、...
i18n_tools 使用I18n库在 Rails 和 Ruby 应用程序中查找丢失和未使用的翻译的非常简单的 rake 任务。安装 gem install i18n_tools用法如果您在 Rails 中使用 bundler,请将以下内容添加到您的Gemfile : group :...
devise-i18n, 设计 gem的翻译 devise-i18n 设计"是一种基于warden的Rails 灵活认证方案"。 国际化( aka i18n ) 是一个"计算机软件适应不同语言。区域差异和目标市场技术要求的方法"。在控制器。模型和其他领域中支持...
Ruby-i18n社区还提供了许多扩展和工具,如`i18n-tasks`用于管理翻译任务,`i18n-spec`用于测试翻译的正确性,以及`gettext_i18n_rails`等工具,它们提供了类似Gettext的翻译工作流程。 通过理解和掌握Ruby-i18n库...
MailForm库是专门为简化这一过程而设计的,它允许开发者直接从Rails的表单中发送邮件,并且提供了I18n(国际化)支持、验证功能以及添加附件和请求信息的能力。这个库由Plataformatec开发,其最新版本为bd43996。 ...
如果要在没有Rails的情况下使用此库,则只需将i18n添加到Gemfile : gem 'i18n' 然后使用一些翻译和默认语言环境配置I18n: I18n . load_path << Dir [ File . expand_path ( "config/locales" ) + "/*....
i18n-tasks可以与使用ruby 任何项目一起使用(Rails中的默认设置)。 将i18n任务添加到Gemfile中: gem 'i18n-tasks' , '~> 0.9.33' 复制默认: $ cp $( i18n-tasks gem-path ) /templates/config/i18n-tasks....
I18n:Bamboo monkey 修补 Rails I18n 模块,并将强制所有对 I18n.translate (I18n.t) 和 I18n.localize (I18n.l) 的调用返回所有可用语言环境中最长的翻译或本地化值。 出于显而易见的原因(猴子补丁 :anxious_face...
Rails这样做:使用嵌套的yml文件的I18n.t('syntax.with.lots.of.dots')我们这样做: _('Just translate my damn text!')使用简单,平坦的mo / po / yml文件,或者直接从db要使用I18n调用,请添加syntax.with.lots....
Ruby(不带Rails)如果要在不带Rails的情况下使用此库,则只需将i18n添加到Gemfile中:gem'i18n',然后使用一些翻译和默认语言环境配置I18n:I18n.load_path << Dir [File.expand_path (“配置/语言环境”)+...
vim-localorie Localorie是一个Vim插件,可以更轻松地使用Rails i18n语言环境文件。查找翻译将光标放在Rails视图或控制器中的i18n键上,调用localorie#translate()用该键的所有翻译内容填充localorie#translate()或...