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. Internationalize your rails app
    (the stuff they don't tell you)
    Austin Flores | @unflores | [email protected]

    View full-size slide

  2. I18n
    The usage that we expect:
    <%= t('some.string.value') %>
    Renders:
    My Value
    Mi Valor
    Ma Valeur

    View full-size slide

  3. Brainstorm eh?

    How to we store the locale between requests?

    How can we store anything between requests?

    View full-size slide

  4. 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

    View full-size slide

  5. 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)

    View full-size slide

  6. Le taf

    Locale switcher

    Scoping incoming params

    Setting the locale

    Keeping the current locale

    View full-size slide

  7. Locale Switcher
    # Locale Switcher
    <%= t('change_locale') %>

    <% I18n.available_locales.each do |locale| %>
    value='<%= url_for_locale(locale) %>'
    selected='<%= locale == I18n.locale %>'
    <%= locale %>

    <% end %>

    # 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();
    });

    View full-size slide

  8. 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

    View full-size slide

  9. Setting locale based on params
    # ApplicationController.
    before_action :set_locale
    def set_locale
    I18n.locale == params[:locale] || I18n.default_locale
    end

    View full-size slide

  10. Keeping current locale through
    requests
    def default_url_options(options={})
    { locale: I18n.locale == I18n.default_locale ? nil : I18n.locale }
    end

    View full-size slide