Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Runtime i18n

i18n locale runtime before_action before_filter

  • Please log in to reply
3 replies to this topic

#1 wilsonsilva

wilsonsilva

    Passenger

  • Members
  • 6 posts

Posted 03 October 2013 - 10:53 AM

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?



#2 wilsonsilva

wilsonsilva

    Passenger

  • Members
  • 6 posts

Posted 03 October 2013 - 01:26 PM

I'm trying to avoid this 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
 

 



#3 james

james

    Guard

  • Moderators
  • 221 posts
  • LocationLeeds, U.K.

Posted 04 October 2013 - 05:24 PM

I use locale subdomains

http://railscasts.co...ains-in-rails-3 works just as well in Rails 4 as it does in Rails 3

so you can do

 

http://en.lvh.me:3000/

http://es.lvh.me:3000/

 

or whatever

 

In my application controller I have a filter

    before_action :set_locale
        
    private

    def set_locale
        I18n.locale = extract_locale_from_subdomain || I18n.default_locale
        @current_locale = I18n.locale
    # logger.debug("@@@@ Locale #{I18n.locale} request: #{request.subdomains.inspect}, Available #{I18n.available_locales.inspect} ")
    end
        
    # Get locale code from request subdomain (like http://it.application.local:3000)
    def extract_locale_from_subdomain
        parsed_locale = request.subdomains.first
        if parsed_locale
            parsed_locale.to_sym
            I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
        end
    end

which is fine.

 

You can't avoid filters to determine the locale. What is the issue?


Programming is just about problem solving!


#4 wilsonsilva

wilsonsilva

    Passenger

  • Members
  • 6 posts

Posted 08 October 2013 - 04:30 PM

You can't avoid filters to determine the locale. What is the issue?

 

Too bad. I was just trying to reduce the number of method calls. Thanks.







Also tagged with one or more of these keywords: i18n, locale, runtime, before_action, before_filter

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users