This cop scans only the tests files by default, but we prefer to scan all application Ruby files, so when a developer uses the class method `I18n.locale=`, the cop will embrace using the method `I18n.with_locale` instead. By doing this way, the cop will help developers to avoid unexpected translation errors. Quoting the Rails 6 guides: > I18n.locale can leak into subsequent requests served by the same thread/process if it is not consistently set in every controller. For example executing I18n.locale = :es in one POST requests will have effects for all later requests to controllers that don't set the locale, but only in that particular thread/process. For that reason, instead of I18n.locale = you can use I18n.with_locale which does not have this leak issue. Now we enabled the cop for all application Ruby files; we have to remove the assignments at the controller level to set the request locale. As Rails 6 guides suggest [1], we can use the `around_action` controller callback to set each request locale without breaking the rule. This cop will warn CONSUL developers when using `I18n.locale` assignment embracing them to use the `I18n.with_locale`instead. [1] https://guides.rubyonrails.org/i18n.html#managing-the-locale-across-requests
40 lines
1.0 KiB
Ruby
40 lines
1.0 KiB
Ruby
class SubscriptionsController < ApplicationController
|
|
before_action :set_user
|
|
around_action :set_user_locale
|
|
skip_authorization_check
|
|
|
|
def edit
|
|
end
|
|
|
|
def update
|
|
@user.update!(subscriptions_params)
|
|
redirect_to edit_subscriptions_path(token: @user.subscriptions_token),
|
|
notice: t("flash.actions.save_changes.notice")
|
|
end
|
|
|
|
private
|
|
|
|
def set_user
|
|
@user = if params[:token].present?
|
|
User.find_by!(subscriptions_token: params[:token])
|
|
else
|
|
current_user || raise(CanCan::AccessDenied)
|
|
end
|
|
end
|
|
|
|
def subscriptions_params
|
|
params.require(:user).permit(allowed_params)
|
|
end
|
|
|
|
def allowed_params
|
|
[:email_on_comment, :email_on_comment_reply, :email_on_direct_message, :email_digest, :newsletter]
|
|
end
|
|
|
|
def set_user_locale(&action)
|
|
if params[:locale].blank?
|
|
session[:locale] = I18n.available_locales.find { |locale| locale == @user.locale&.to_sym }
|
|
end
|
|
I18n.with_locale(session[:locale], &action)
|
|
end
|
|
end
|