SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
INTERNATIONALIZATION FOR RUBY
https://lingohub.com MADE WITH BY LINGOHUB
RUBY i18n
INTERNATIONALIZATION FOR PLAIN RUBY: THE RUBY i18n GEM
− Ruby i18n allows translation and localization,interpolation of values to translations,
pluralization,customizable transliteration to ASCII, flexible defaults, bulk lookup,lambdas
as translation data, custom key/scope separator, and custom exception handlers.
− The gem is split in two parts:
− Public API
− Default backend
− YAML (.yml) or plain Ruby (.rb) files are used for storing translationsin SimpleStore,still
YAML is the preferred option among Ruby developers.
https://lingohub.com MADE WITH BY LINGOHUB
INTERNATIONALIZATION AND THE YAML RESOURCE FILE FORMAT
KEY FEATURES OF YAML
− Information is stored in key-value pairs delimited with colon ( : )
− Keys can be nested (scoped)
− i18n expects the root key to correspond to the locale of the content
− The “leaf key” has to have a value
− Values can be escaped
− Correct and consistent line indentation is important for preserving the key hierarchy
https://lingohub.com MADE WITH BY LINGOHUB
INTERNATIONALIZATION AND THE YAML RESOURCE FILE FORMAT
KEY FEATURES OF YAML
− Lines starting with a hash tag sign ( # ) preceded with any number of white-space are
ignored by the parser (treated as a comment)
− Place-holder syntax is: %{name}, where “name” can consist of multiple non-white-space
characters
− UTF-8 encoding is usually used for YAML resource files
https://lingohub.com MADE WITH BY LINGOHUB
EXAMPLE YAML FILE
https://lingohub.com MADE WITH BY LINGOHUB
INSTALLATION AND SETUP
1. gem installation
2. Change the directoryto the location
where the sample YAML file was saved
and start the irb (interactive ruby shell).
3. Check the current locale. (By default it
is English)
4. Changing it something else is easy.
gem  install  i18n
2.0.0p247  :001  >  require  ‘i18n’
=>  true
2.0.0p247  :002  >  I18n.locale
=>  :en
2.0.0p247  :003  >  I18n.locale  =  :de
=>  :de
https://lingohub.com MADE WITH BY LINGOHUB
TRANSALTION LOOKUP
− Lookup one of the phrases from our
YAML file example
− The translation is missing because we
haven’t loaded the file. Load all .yml and
.rb files in the current directory.
− Retry accessing the English translation
with the key ‘world’
2.0.0p247  :004  >  I18n.translate  :world,  
:scope  =>  ‘greetings.hello’
=>  “translation  missing:  en.hello.world”
2.0.0p247  :005  >  I18n.load_path  =  
Dir[‘./*.yml,  ‘./*.rb’]
=>  [“./en.yml”]
2.0.0p247  :006  >  I18n.translate  :world,  
:scope  =>  ‘greetings.hello’
=>  “Hello  world!”
https://lingohub.com MADE WITH BY LINGOHUB
TRANSALTION LOOKUP
− A local can also be explicitly passed
− When passing the phrase key, a symbol or
string can be used, and a scope can be an
array or dot-separated. Combinations of
them are valid too.
2.0.0p247   :007  >  I18n.translate   :world,  :scope  
=>  ‘greetings.hello’,   :locale  =>  :en
=>  “Hello  world!”
I18n.translate   ‘greetings.hello.world’
I18n.translate   ‘hello.world’,   :scope  =>  
:greetings
I18n.translate   ‘hello.world’,   :scope  =>  
‘greetings’
I18n.translate   :world,  :scope  =>  
‘greetings.hello’
I18n.translate   :world,  scope:  [:greetings,  
:hello]
https://lingohub.com MADE WITH BY LINGOHUB
TRANSALTION LOOKUP
− Translate the key :missing and the key
:also_missing
− Variables can be interpolated to the
translation
− Pass an array of keys to look up multiple
translations at once
− A key can translate to a hash of grouped
translations
2.0.0p247   :008  >  I18n.translate   :missing,  
default:  [:also_missing,   ‘Not  here’]
=>  ‘Not  here’
2.0.0p247   :009  >  I18n.translate   :user,  :scope  
=>  [:greetings,   :hello],  :user  =>  ‘Ela’
=>  “Hello  Ela!”
2.0.0p247   :010  >  I18n.translate   [:world,  
:friend],   :scope  =>  [:greetings,   :hello]
=>  [“Hello  World!”,  “Hello  Friend!”]
2.0.0p247   :011  >  I18n.translate   :hello,  :scope  
=>  [:greetings]   =>  {:world=>”Hello   World!”,  
:user=>”Hello   %{user}”,  :friend=>”Hello  
Friend!”}
https://lingohub.com MADE WITH BY LINGOHUB
PLUARLIZATION OPTION IN i18n FOR RUBY
− The i18n API providesa flexible
pluralization feature adaptingto the
different grammar of languages.
− The :count interpolation isinterpolated to
the translation and used to pick a
pluralization from the translations
2.0.0p247  :012  >  I18n.translate  :messages,  
:scope  =>  :inbox,  :count  =>  1
=>  “You  have  one  message  in  your  inbox.”
2.0.0p247  :013  >  I18n.translate  :messages,  
:scope  =>  :inbox,  :count  =>  39
=>  “You  have  39  messages  in  your  inbox.”
https://lingohub.com MADE WITH BY LINGOHUB
SETTING UP DATE AND TIME LOCALIZATION
− Pass the Time object to I18n.localize to
localize the time format. Pick a format by
passing the :format option
2.0.0p247  :014  >  I18n.localize  Time.now
=>  “Wed,  14  Aug  2013  13:34:49  +0200”
2.0.0p247  :015  >  I18n.localize  Time.now,  
:format  =>  :short
=>  “14  Aug  13:34”
https://lingohub.com MADE WITH BY LINGOHUB
⟶ Instead of I18n.localize,a shorter alias can be used: I18n.l.
i18n – THE DEFAULT INTERNATIONALIZATION SOLUTION FOR RUBY ON RAILS
− Ruby adds all .rb and .yml files from the config/locales directory to translations load path
automatically.
− By default, Rials expects that all the resource files are kept in config/locales.
− You can change some settings by overriding the defaults in application.rb
− Organize the resource files in subdirectories
− Set :de as the default locale
− Set :en, :de and :fr as available locales
https://lingohub.com MADE WITH BY LINGOHUB
Config.i18n.load_path  +=  
Dir[Rails.root.join(‘config/locales/**/*.{rb,ym
l}’]
config.i18n.default_locale  =  :de
Config.i18n.available_locales  =  [:en,  :de,  :fr]
PASSING THE LOCALE AS A QUERY PARAMETER WITHIN THE URL
− Set the locale in before_action in the
ApplicationController
− This requires passing the locale as a URL
query parameter and adding it to all the
links within the application.
− Rails comes with a helper method that
can be overridden
before_action :set_locale
Def set_locale
I18n.locale  =  params[:locale]  ||  
I18n.default_locale
end
#  app/controllers/application_controller.rb
def default_url_options(options={})
{  :locale  =>  I18n.locale  }
end
https://lingohub.com MADE WITH BY LINGOHUB
PASSING THE LOCALE AS A PART OF THE URL PATH
It is cleaner to have the locale information
at the beginning of the path instead of the
end:
http://localhost:3000/sr/ vs http://localhost:
3000/?locale=sr.
You can do so with the “over-riding
default_url_options”strategy. Just set up the
routes with the scoping option.
#  config/routes.rb
scope  “(:locale)”,  locale:  /en|sr/  do
resources  :books
end
https://lingohub.com MADE WITH BY LINGOHUB
PASSING THE LOCALE AS A DOMAIN NAME OR A SUBDOMAIN
− Setting the locale from the domain name
or subdomain makes the locale very
obvious and search engines like this
approach too.
− Do so by adding a before_action to the
ApplicationController.
before_action :set_locale
def set_locale
#extracting from the domain name
I18n.locale  =  extract_locale_from_tld ||  I18n.default_locale  
#extracting from subdomain:  
#I18n.locale  =  extract_locale_from_subdomain ||  I18n.default_locale  
end  
def extract_locale_from_tld
parsed_locale =  request.host.split('.').last
I18n.available_locales.include?(parsed_locale.to_sym)  ?  
parsed_locale :  nil
end  
def extract_locale_from_subdomain
parsed_locale =  request.subdomains.first
I18n.available_locales.include?(parsed_locale.to_sym)  ?  
parsed_locale :  nil
end
https://lingohub.com MADE WITH BY LINGOHUB
SETTING THE LOCALE FROM CLIENT-SUPPLIED INFORMATION
− Information other than the page URL can
be used to set the appropriate locale for
the current user.
− An example for a trivial implementation of
using an Accept-Language header
https://lingohub.com MADE WITH BY LINGOHUB
I18n.locale  =  current_user.locale
def set_locale
I18n.locale  =  
extract_locale_from_accept_language_header
end  
private  
def extract_locale_from_accept_language_header
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/
^[a-­‐z]{2}/).first  
end
TRANSLATION LOOKUP AND DATE/TIME LOCALIZATION BY RUBY ON RAILS
Rails adds t (translate) and l (localize) helper
methods to controllers. They will catch
missing translationsand wrap the resulting
error message into a <span>.
#instead  of  I18n.translate  :hello
t  :hello
#instead  of  I18n.localize  Time.now
l Time.now
https://lingohub.com MADE WITH BY LINGOHUB
USING SAFE HTML TRANSLATIONS IN RUBY ON RAILS
− Keys with a ‘_html’ suffix and keys named
‘html’ are marked as HTML safe. Use
them without escaping.
#config/locales/en.yml
en:
welcome:  <b>welcome!</b>
hello_html:  <b>hello!</b>
title:
html:  <b>title!</b>
#  app/views/home/index.html.erb
<div><%=  t(‘welcome’)  %></div>
<div><%=  raw  t(‘welcome’)  %></div>
<div><%=  t(‘hello_html’)  %></div>
<div><%=  t(‘title.html’)  %></div>
https://lingohub.com MADE WITH BY LINGOHUB
TRANSLATION FOR ACTIVE RECORD MODELS
− Methods Model.model_name.human and
Model.human_attribute_name(attribute)
can be used to transparentlylook up
translationsfor model and attribute
names.
en:  
activerecord:
models:
user:  Dude
attributes:  
user:
login:  “Handle”
#  will  translate  User  
attribute  “login”  as  “Handle”
https://lingohub.com MADE WITH BY LINGOHUB
ERROR MESSAGE SCOPES
For example,if there is an ActiveRecord
model “User” that has the :presence
validation for :name, the key for the
message would be :blank. ActiveRecord will
look up for this key in several namespaces,
in this order:
activerecord.errors.models.[model_name].attr
ibutes.[attribute_name]
activerecord.errors.models.[model_name]
activerecord.errors.messages
errors.attributes.[attribute_name]
errors.messages
https://lingohub.com MADE WITH BY LINGOHUB
SENATRA AND PADRINO
https://lingohub.com MADE WITH BY LINGOHUB
I18n FOR
i18n FOR SINATRA
Set up Sinatra to use i18n gem for
internationalization
require  ‘i18n’
require  ’i18n/backend/fallbacks’
configure
I18n::Backend::Simple.send(:include,  
I18n::Backend::Fallbacks)
I18n.load_path,  Dir
[File.join(settings.root,  ‘locales’,  
‘*.yml’)]
I18n.backend.load_translations
end
https://lingohub.com MADE WITH BY LINGOHUB
i18n FOR SINATRA
before  ‘/:locale/*’   do
I18n.locale   =  params[:locale]
request.path_info =  ‘/’  +  
params[:splat   ]  [0]
end
before  do
if  (locale  =  
request.host.split(‘.’)[0])   !=  ‘www’
I18n.locale   =  locale
end
end
use  Rack::Locale
https://lingohub.com MADE WITH BY LINGOHUB
Passing the locale
− Specific URLs
− Dedicated subdomains
i18n FOR SINATRA
use  Rack::Locale
helpers   do
def t(*args)
I18n.t(*args)
end
def l(*args)
I18n.l(*args)
end
end
helpers   do
def find_template(views,   name,   engine,   &block)
I18n.fallbacks[I18n.locale].each   {  
|locale|  
super(views,  
“#{name}.#{locale}”,   engine,   &block)}
super(views,   name,   engine,   &block)
end
end
https://lingohub.com MADE WITH BY LINGOHUB
Passing the locale
− Browser preference (requires rack-
contrib)
i18n FOR PADRINO
Localization is fully supported in
− padrino-core (date formats, time formats etc.)
− padrino-admin (admin language, orm fields, orm errors, etc.)
− padrino-helpers(currency, percentage, precision,duration,etc.)
Setting up the default locale in config/boot.rb
https://lingohub.com MADE WITH BY LINGOHUB
Padrino.before_load do
I18n.locale  =  :en
end
BROUGHT TO YOU BY LINGOHUB
ANJA OBERMÜLLER
BUSINESS DEVELOPMENT& MARKETING AT
LINGOHUB
anja.obermueller@lingohub.com
@LingoHub
@anjaobermueller
Read the whole article.
https://lingohub.com MADE WITH BY LINGOHUB

Más contenido relacionado

Similar a Ruby i18n - internationalization for ruby

The Ruby On Rails I18n Core Api
The Ruby On Rails I18n Core ApiThe Ruby On Rails I18n Core Api
The Ruby On Rails I18n Core ApiNTT DATA Americas
 
Internationalization in Rails 2.2
Internationalization in Rails 2.2Internationalization in Rails 2.2
Internationalization in Rails 2.2Belighted
 
Internationalization in Rails 2.2
Internationalization in Rails 2.2Internationalization in Rails 2.2
Internationalization in Rails 2.2Nicolas Jacobeus
 
Shipping your product overseas!
Shipping your product overseas!Shipping your product overseas!
Shipping your product overseas!Diogo Busanello
 
Log grid root
Log grid rootLog grid root
Log grid rootopenmi
 
Multi Lingual Websites In Umbraco
Multi Lingual Websites In UmbracoMulti Lingual Websites In Umbraco
Multi Lingual Websites In UmbracoPaul Marden
 
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...Andrejs Prokopjevs
 
All the language support in Drupal 8 - At Drupalaton 2014
All the language support in Drupal 8 - At Drupalaton 2014All the language support in Drupal 8 - At Drupalaton 2014
All the language support in Drupal 8 - At Drupalaton 2014Gábor Hojtsy
 
The (mutable) config management showdown
The (mutable) config management showdownThe (mutable) config management showdown
The (mutable) config management showdownBob Killen
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and othersYusuke Wada
 
Five Real-World Strategies for Perforce Streams
Five Real-World Strategies for Perforce StreamsFive Real-World Strategies for Perforce Streams
Five Real-World Strategies for Perforce StreamsPerforce
 
Internationalisation In Rails
Internationalisation In RailsInternationalisation In Rails
Internationalisation In RailsRishav Dixit
 
Plone i18n, LinguaPlone
Plone i18n, LinguaPlonePlone i18n, LinguaPlone
Plone i18n, LinguaPloneQuintagroup
 
Localizing web sites in ruby on rails
Localizing web sites in ruby on railsLocalizing web sites in ruby on rails
Localizing web sites in ruby on railsBethany Rentz
 

Similar a Ruby i18n - internationalization for ruby (20)

The Ruby On Rails I18n Core Api
The Ruby On Rails I18n Core ApiThe Ruby On Rails I18n Core Api
The Ruby On Rails I18n Core Api
 
Internationalization in Rails 2.2
Internationalization in Rails 2.2Internationalization in Rails 2.2
Internationalization in Rails 2.2
 
Internationalization in Rails 2.2
Internationalization in Rails 2.2Internationalization in Rails 2.2
Internationalization in Rails 2.2
 
Rails i18n
Rails i18nRails i18n
Rails i18n
 
Shipping your product overseas!
Shipping your product overseas!Shipping your product overseas!
Shipping your product overseas!
 
Localization in Rails
Localization in RailsLocalization in Rails
Localization in Rails
 
I18n in Rails2.2
I18n in Rails2.2I18n in Rails2.2
I18n in Rails2.2
 
Log grid root
Log grid rootLog grid root
Log grid root
 
Multi Lingual Websites In Umbraco
Multi Lingual Websites In UmbracoMulti Lingual Websites In Umbraco
Multi Lingual Websites In Umbraco
 
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
All the language support in Drupal 8 - At Drupalaton 2014
All the language support in Drupal 8 - At Drupalaton 2014All the language support in Drupal 8 - At Drupalaton 2014
All the language support in Drupal 8 - At Drupalaton 2014
 
Creating messages
Creating messagesCreating messages
Creating messages
 
The (mutable) config management showdown
The (mutable) config management showdownThe (mutable) config management showdown
The (mutable) config management showdown
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
 
Five Real-World Strategies for Perforce Streams
Five Real-World Strategies for Perforce StreamsFive Real-World Strategies for Perforce Streams
Five Real-World Strategies for Perforce Streams
 
Internationalisation In Rails
Internationalisation In RailsInternationalisation In Rails
Internationalisation In Rails
 
Plone i18n, LinguaPlone
Plone i18n, LinguaPlonePlone i18n, LinguaPlone
Plone i18n, LinguaPlone
 
Localizing web sites in ruby on rails
Localizing web sites in ruby on railsLocalizing web sites in ruby on rails
Localizing web sites in ruby on rails
 
ColdBox i18N
ColdBox i18N ColdBox i18N
ColdBox i18N
 

Más de LingoHub

Infographic preferred online payment methods
Infographic preferred online payment methodsInfographic preferred online payment methods
Infographic preferred online payment methodsLingoHub
 
Mobile app localization - markets and opportunities
Mobile app localization - markets and opportunitiesMobile app localization - markets and opportunities
Mobile app localization - markets and opportunitiesLingoHub
 
Stripe subscription and VAT handling
Stripe subscription and VAT handlingStripe subscription and VAT handling
Stripe subscription and VAT handlingLingoHub
 
Lean translation management for better results
Lean translation management for better resultsLean translation management for better results
Lean translation management for better resultsLingoHub
 
Gettext i18n system - internationalization for gettext
Gettext i18n system - internationalization for gettextGettext i18n system - internationalization for gettext
Gettext i18n system - internationalization for gettextLingoHub
 
7 tips for going international with your website
7 tips for going international with your website7 tips for going international with your website
7 tips for going international with your websiteLingoHub
 
Software Localization made easy
Software Localization made easySoftware Localization made easy
Software Localization made easyLingoHub
 

Más de LingoHub (7)

Infographic preferred online payment methods
Infographic preferred online payment methodsInfographic preferred online payment methods
Infographic preferred online payment methods
 
Mobile app localization - markets and opportunities
Mobile app localization - markets and opportunitiesMobile app localization - markets and opportunities
Mobile app localization - markets and opportunities
 
Stripe subscription and VAT handling
Stripe subscription and VAT handlingStripe subscription and VAT handling
Stripe subscription and VAT handling
 
Lean translation management for better results
Lean translation management for better resultsLean translation management for better results
Lean translation management for better results
 
Gettext i18n system - internationalization for gettext
Gettext i18n system - internationalization for gettextGettext i18n system - internationalization for gettext
Gettext i18n system - internationalization for gettext
 
7 tips for going international with your website
7 tips for going international with your website7 tips for going international with your website
7 tips for going international with your website
 
Software Localization made easy
Software Localization made easySoftware Localization made easy
Software Localization made easy
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Ruby i18n - internationalization for ruby

  • 1. INTERNATIONALIZATION FOR RUBY https://lingohub.com MADE WITH BY LINGOHUB RUBY i18n
  • 2. INTERNATIONALIZATION FOR PLAIN RUBY: THE RUBY i18n GEM − Ruby i18n allows translation and localization,interpolation of values to translations, pluralization,customizable transliteration to ASCII, flexible defaults, bulk lookup,lambdas as translation data, custom key/scope separator, and custom exception handlers. − The gem is split in two parts: − Public API − Default backend − YAML (.yml) or plain Ruby (.rb) files are used for storing translationsin SimpleStore,still YAML is the preferred option among Ruby developers. https://lingohub.com MADE WITH BY LINGOHUB
  • 3. INTERNATIONALIZATION AND THE YAML RESOURCE FILE FORMAT KEY FEATURES OF YAML − Information is stored in key-value pairs delimited with colon ( : ) − Keys can be nested (scoped) − i18n expects the root key to correspond to the locale of the content − The “leaf key” has to have a value − Values can be escaped − Correct and consistent line indentation is important for preserving the key hierarchy https://lingohub.com MADE WITH BY LINGOHUB
  • 4. INTERNATIONALIZATION AND THE YAML RESOURCE FILE FORMAT KEY FEATURES OF YAML − Lines starting with a hash tag sign ( # ) preceded with any number of white-space are ignored by the parser (treated as a comment) − Place-holder syntax is: %{name}, where “name” can consist of multiple non-white-space characters − UTF-8 encoding is usually used for YAML resource files https://lingohub.com MADE WITH BY LINGOHUB
  • 6. INSTALLATION AND SETUP 1. gem installation 2. Change the directoryto the location where the sample YAML file was saved and start the irb (interactive ruby shell). 3. Check the current locale. (By default it is English) 4. Changing it something else is easy. gem  install  i18n 2.0.0p247  :001  >  require  ‘i18n’ =>  true 2.0.0p247  :002  >  I18n.locale =>  :en 2.0.0p247  :003  >  I18n.locale  =  :de =>  :de https://lingohub.com MADE WITH BY LINGOHUB
  • 7. TRANSALTION LOOKUP − Lookup one of the phrases from our YAML file example − The translation is missing because we haven’t loaded the file. Load all .yml and .rb files in the current directory. − Retry accessing the English translation with the key ‘world’ 2.0.0p247  :004  >  I18n.translate  :world,   :scope  =>  ‘greetings.hello’ =>  “translation  missing:  en.hello.world” 2.0.0p247  :005  >  I18n.load_path  =   Dir[‘./*.yml,  ‘./*.rb’] =>  [“./en.yml”] 2.0.0p247  :006  >  I18n.translate  :world,   :scope  =>  ‘greetings.hello’ =>  “Hello  world!” https://lingohub.com MADE WITH BY LINGOHUB
  • 8. TRANSALTION LOOKUP − A local can also be explicitly passed − When passing the phrase key, a symbol or string can be used, and a scope can be an array or dot-separated. Combinations of them are valid too. 2.0.0p247   :007  >  I18n.translate   :world,  :scope   =>  ‘greetings.hello’,   :locale  =>  :en =>  “Hello  world!” I18n.translate   ‘greetings.hello.world’ I18n.translate   ‘hello.world’,   :scope  =>   :greetings I18n.translate   ‘hello.world’,   :scope  =>   ‘greetings’ I18n.translate   :world,  :scope  =>   ‘greetings.hello’ I18n.translate   :world,  scope:  [:greetings,   :hello] https://lingohub.com MADE WITH BY LINGOHUB
  • 9. TRANSALTION LOOKUP − Translate the key :missing and the key :also_missing − Variables can be interpolated to the translation − Pass an array of keys to look up multiple translations at once − A key can translate to a hash of grouped translations 2.0.0p247   :008  >  I18n.translate   :missing,   default:  [:also_missing,   ‘Not  here’] =>  ‘Not  here’ 2.0.0p247   :009  >  I18n.translate   :user,  :scope   =>  [:greetings,   :hello],  :user  =>  ‘Ela’ =>  “Hello  Ela!” 2.0.0p247   :010  >  I18n.translate   [:world,   :friend],   :scope  =>  [:greetings,   :hello] =>  [“Hello  World!”,  “Hello  Friend!”] 2.0.0p247   :011  >  I18n.translate   :hello,  :scope   =>  [:greetings]   =>  {:world=>”Hello   World!”,   :user=>”Hello   %{user}”,  :friend=>”Hello   Friend!”} https://lingohub.com MADE WITH BY LINGOHUB
  • 10. PLUARLIZATION OPTION IN i18n FOR RUBY − The i18n API providesa flexible pluralization feature adaptingto the different grammar of languages. − The :count interpolation isinterpolated to the translation and used to pick a pluralization from the translations 2.0.0p247  :012  >  I18n.translate  :messages,   :scope  =>  :inbox,  :count  =>  1 =>  “You  have  one  message  in  your  inbox.” 2.0.0p247  :013  >  I18n.translate  :messages,   :scope  =>  :inbox,  :count  =>  39 =>  “You  have  39  messages  in  your  inbox.” https://lingohub.com MADE WITH BY LINGOHUB
  • 11. SETTING UP DATE AND TIME LOCALIZATION − Pass the Time object to I18n.localize to localize the time format. Pick a format by passing the :format option 2.0.0p247  :014  >  I18n.localize  Time.now =>  “Wed,  14  Aug  2013  13:34:49  +0200” 2.0.0p247  :015  >  I18n.localize  Time.now,   :format  =>  :short =>  “14  Aug  13:34” https://lingohub.com MADE WITH BY LINGOHUB ⟶ Instead of I18n.localize,a shorter alias can be used: I18n.l.
  • 12. i18n – THE DEFAULT INTERNATIONALIZATION SOLUTION FOR RUBY ON RAILS − Ruby adds all .rb and .yml files from the config/locales directory to translations load path automatically. − By default, Rials expects that all the resource files are kept in config/locales. − You can change some settings by overriding the defaults in application.rb − Organize the resource files in subdirectories − Set :de as the default locale − Set :en, :de and :fr as available locales https://lingohub.com MADE WITH BY LINGOHUB Config.i18n.load_path  +=   Dir[Rails.root.join(‘config/locales/**/*.{rb,ym l}’] config.i18n.default_locale  =  :de Config.i18n.available_locales  =  [:en,  :de,  :fr]
  • 13. PASSING THE LOCALE AS A QUERY PARAMETER WITHIN THE URL − Set the locale in before_action in the ApplicationController − This requires passing the locale as a URL query parameter and adding it to all the links within the application. − Rails comes with a helper method that can be overridden before_action :set_locale Def set_locale I18n.locale  =  params[:locale]  ||   I18n.default_locale end #  app/controllers/application_controller.rb def default_url_options(options={}) {  :locale  =>  I18n.locale  } end https://lingohub.com MADE WITH BY LINGOHUB
  • 14. PASSING THE LOCALE AS A PART OF THE URL PATH It is cleaner to have the locale information at the beginning of the path instead of the end: http://localhost:3000/sr/ vs http://localhost: 3000/?locale=sr. You can do so with the “over-riding default_url_options”strategy. Just set up the routes with the scoping option. #  config/routes.rb scope  “(:locale)”,  locale:  /en|sr/  do resources  :books end https://lingohub.com MADE WITH BY LINGOHUB
  • 15. PASSING THE LOCALE AS A DOMAIN NAME OR A SUBDOMAIN − Setting the locale from the domain name or subdomain makes the locale very obvious and search engines like this approach too. − Do so by adding a before_action to the ApplicationController. before_action :set_locale def set_locale #extracting from the domain name I18n.locale  =  extract_locale_from_tld ||  I18n.default_locale   #extracting from subdomain:   #I18n.locale  =  extract_locale_from_subdomain ||  I18n.default_locale   end   def extract_locale_from_tld parsed_locale =  request.host.split('.').last I18n.available_locales.include?(parsed_locale.to_sym)  ?   parsed_locale :  nil end   def extract_locale_from_subdomain parsed_locale =  request.subdomains.first I18n.available_locales.include?(parsed_locale.to_sym)  ?   parsed_locale :  nil end https://lingohub.com MADE WITH BY LINGOHUB
  • 16. SETTING THE LOCALE FROM CLIENT-SUPPLIED INFORMATION − Information other than the page URL can be used to set the appropriate locale for the current user. − An example for a trivial implementation of using an Accept-Language header https://lingohub.com MADE WITH BY LINGOHUB I18n.locale  =  current_user.locale def set_locale I18n.locale  =   extract_locale_from_accept_language_header end   private   def extract_locale_from_accept_language_header request.env['HTTP_ACCEPT_LANGUAGE'].scan(/ ^[a-­‐z]{2}/).first   end
  • 17. TRANSLATION LOOKUP AND DATE/TIME LOCALIZATION BY RUBY ON RAILS Rails adds t (translate) and l (localize) helper methods to controllers. They will catch missing translationsand wrap the resulting error message into a <span>. #instead  of  I18n.translate  :hello t  :hello #instead  of  I18n.localize  Time.now l Time.now https://lingohub.com MADE WITH BY LINGOHUB
  • 18. USING SAFE HTML TRANSLATIONS IN RUBY ON RAILS − Keys with a ‘_html’ suffix and keys named ‘html’ are marked as HTML safe. Use them without escaping. #config/locales/en.yml en: welcome:  <b>welcome!</b> hello_html:  <b>hello!</b> title: html:  <b>title!</b> #  app/views/home/index.html.erb <div><%=  t(‘welcome’)  %></div> <div><%=  raw  t(‘welcome’)  %></div> <div><%=  t(‘hello_html’)  %></div> <div><%=  t(‘title.html’)  %></div> https://lingohub.com MADE WITH BY LINGOHUB
  • 19. TRANSLATION FOR ACTIVE RECORD MODELS − Methods Model.model_name.human and Model.human_attribute_name(attribute) can be used to transparentlylook up translationsfor model and attribute names. en:   activerecord: models: user:  Dude attributes:   user: login:  “Handle” #  will  translate  User   attribute  “login”  as  “Handle” https://lingohub.com MADE WITH BY LINGOHUB
  • 20. ERROR MESSAGE SCOPES For example,if there is an ActiveRecord model “User” that has the :presence validation for :name, the key for the message would be :blank. ActiveRecord will look up for this key in several namespaces, in this order: activerecord.errors.models.[model_name].attr ibutes.[attribute_name] activerecord.errors.models.[model_name] activerecord.errors.messages errors.attributes.[attribute_name] errors.messages https://lingohub.com MADE WITH BY LINGOHUB
  • 21. SENATRA AND PADRINO https://lingohub.com MADE WITH BY LINGOHUB I18n FOR
  • 22. i18n FOR SINATRA Set up Sinatra to use i18n gem for internationalization require  ‘i18n’ require  ’i18n/backend/fallbacks’ configure I18n::Backend::Simple.send(:include,   I18n::Backend::Fallbacks) I18n.load_path,  Dir [File.join(settings.root,  ‘locales’,   ‘*.yml’)] I18n.backend.load_translations end https://lingohub.com MADE WITH BY LINGOHUB
  • 23. i18n FOR SINATRA before  ‘/:locale/*’   do I18n.locale   =  params[:locale] request.path_info =  ‘/’  +   params[:splat   ]  [0] end before  do if  (locale  =   request.host.split(‘.’)[0])   !=  ‘www’ I18n.locale   =  locale end end use  Rack::Locale https://lingohub.com MADE WITH BY LINGOHUB Passing the locale − Specific URLs − Dedicated subdomains
  • 24. i18n FOR SINATRA use  Rack::Locale helpers   do def t(*args) I18n.t(*args) end def l(*args) I18n.l(*args) end end helpers   do def find_template(views,   name,   engine,   &block) I18n.fallbacks[I18n.locale].each   {   |locale|   super(views,   “#{name}.#{locale}”,   engine,   &block)} super(views,   name,   engine,   &block) end end https://lingohub.com MADE WITH BY LINGOHUB Passing the locale − Browser preference (requires rack- contrib)
  • 25. i18n FOR PADRINO Localization is fully supported in − padrino-core (date formats, time formats etc.) − padrino-admin (admin language, orm fields, orm errors, etc.) − padrino-helpers(currency, percentage, precision,duration,etc.) Setting up the default locale in config/boot.rb https://lingohub.com MADE WITH BY LINGOHUB Padrino.before_load do I18n.locale  =  :en end
  • 26. BROUGHT TO YOU BY LINGOHUB ANJA OBERMÜLLER BUSINESS DEVELOPMENT& MARKETING AT LINGOHUB anja.obermueller@lingohub.com @LingoHub @anjaobermueller Read the whole article. https://lingohub.com MADE WITH BY LINGOHUB