Austin Flores

Austin Flores

527d9857d91751ee90865645c8507cf6?s=128

Austin Flores

June 10, 2017
Tweet

Transcript

  1. Internationalize your rails app (the stuff they don't tell you)

    Austin Flores | @unflores | me@austinflores.com
  2. None
  3. None
  4. None
  5. None
  6. 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>
  7. Brainstorm eh? • How to we store the locale between

    requests? • How can we store anything between requests?
  8. 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
  9. 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)
  10. La Réquete

  11. Le taf • Locale switcher • Scoping incoming params •

    Setting the locale • Keeping the current locale
  12. 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(); });
  13. 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
  14. None
  15. None
  16. Setting locale based on params # ApplicationController. before_action :set_locale def

    set_locale I18n.locale == params[:locale] || I18n.default_locale end
  17. Keeping current locale through requests def default_url_options(options={}) { locale: I18n.locale

    == I18n.default_locale ? nil : I18n.locale } end
  18. None