-1

Is there a way to set the locale and keep it set between requests without using a before_action/before_filter in the application controller?

I'm trying to avoid my current solution:

class ApplicationController < ActionController::Base
  before_action :set_locale

  def set_locale
    I18n.locale = current_user.locale if current_user
  end  
end

class LocaleController < ApplicationController
  skip_authorization_check

  def index
    locale = params[:locale]
    raise 'Unsupported locale' unless ['en', 'pt'].include?(locale)
    error_message = "Could not set locale" unless current_user.update_column(:locale, locale)
    I18n.locale = current_user.locale if error_message.nil?
    redirect_to :back, :alert => error_message
  end
end

1 Answers1

1

You should use only

class ApplicationController < ActionController::Base

  catrr_accesor :locale_set
  before_action :set_locale :if => lambda {|c| locale_set}


  def set_locale
    I18n.locale = current_user.locale if current_user
    ApplicationController.locale_set = true
  end  
end

As you can see from your code other controllers inherits that.

And maybe you want to do something like:

  def set_locale
    I18n.locale = user_signed_in? ? current_user.locale.to_sym : (params[:local] || I18n.default_locale)
  end

To swing with devise you can end with something like that:

  # get locale of user
  def after_sign_in_path_for(resource_or_scope)
    if resource_or_scope.is_a?(User) && resource_or_scope.locale !=  I18n.locale
      I18n.locale = resource_or_scope.locale.to_sym || I18n.default_locale
    end
    session[:previous_url] || root_path
  end
Jakub Kuchar
  • 1,665
  • 2
  • 23
  • 39
  • I'm trying to avoid the before_filter/before_action methods. –  Oct 03 '13 at 15:54
  • maybe try this with conditional before filter which should run just once, i hope. If still not what you looking for, how about some hooks to devise if you using? – Jakub Kuchar Oct 04 '13 at 02:08