Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Austin Flores

Austin Flores

Austin Flores

June 10, 2017
Tweet

Other Decks in Programming

Transcript

  1. I18n The usage that we expect: <h1><%= t('some.string.value') %></h1> Renders:

    <h1>My Value</h1> <h1>Mi Valor</h1> <h1>Ma Valeur</h1>
  2. Brainstorm eh? • How to we store the locale between

    requests? • How can we store anything between requests?
  3. Manage locales across requests Cookies • User carries it around

    with them • Can't share links • Simpler to set • Sign out loses language URLs • Must pass each request • Locale is explicit • Can share locale • Sign out won't lose locale
  4. What Rails Says • Rails I18n docs – Subdomains(http://fr.wollydo.com/machins) –

    Top Level domains(http://wollydo.fr/machins) – URL parameter(http://wollydo.fr/machins?locale=nl) – URL path(http://wollydo.fr/fr/machins)
  5. Le taf • Locale switcher • Scoping incoming params •

    Setting the locale • Keeping the current locale
  6. Locale Switcher # Locale Switcher <label><%= t('change_locale') %></label> <select class='language_switcher'>

    <% I18n.available_locales.each do |locale| %> <option value='<%= url_for_locale(locale) %>' selected='<%= locale == I18n.locale %>' <%= locale %> </option> <% end %> </select> # URL Helper def url_for_locale(locale) url_for( locale: locale, action: params[:action], controller: params[:controller] ) end # jquery for switch $('select.language_switcher') .change(function(element){ window.location.href = $(this).val(); });
  7. Scope incoming params # route definitions in routes.rb def site_endpoints

    namespace :admin do resources :posts resources :images end resources :posts, only: [:index] end # scoping in routes.rb scope '/(:locale)', constraints: AvailableLocalesConstraint.new do site_endpoints end site_endpoints # constraint class AvailableLocalesConstraint def matches?(request) return unless request.params[:locale] locale = request.params[:locale].to_sym I18n.available_locales.include? locale end end
  8. Setting locale based on params # ApplicationController. before_action :set_locale def

    set_locale I18n.locale == params[:locale] || I18n.default_locale end