ruby-on-railsruby-on-rails-4internationalizationruby-on-rails-5rails-i18n

How can I customise the language of the JSON response in Rails?


I have a controller that has a mobile client. The response is currently in English; however, I'm questioning if there is a way to customise the language of the response.

For example:

English: { "success": false, "message": "Error with your login or password" }

Spanish:{ "success": false, "message": "Error con tu usuario o contraseña" }

And, of course, the content of the "message" is going to be located in the language configuration file that Rails has, as follows.

en.yml

or

es.yml

The following is the function from where the response is generated.

def invalid_login_attempt
    warden.custom_failure!
    render :json => { :success => false, :message=> "Error with your login or password" }, :status => 401
  end

Solution

  • Have you tried I18n.t?

    render :json => { :success => false, :message=> I18n.t('your_key') }, :status => 401
    

    Based on certain criteria, you can set the locale for every request in the ApplicationController; for example:

    before_action :set_locale
    
    def set_locale
      I18n.locale = request.headers["X-Lang"] || I18n.default_locale
    end