ActionPolicy
integrates with i18n
to support localizable full_messages
for reasons and the execution result's message
:
class ApplicationController < ActionController::Base
rescue_from ActionPolicy::Unauthorized do |ex|
p ex.result.message #=> "You do not have access to the stage"
p ex.result.reasons.full_messages #=> ["You do not have access to the stage"]
end
end
The message contains a string for the rule that was called, while full_messages
contains the list of reasons, why ActionPolicy::Unauthorized
has been raised. You can find more information about tracking failure reasons here.
ActionPolicy
doesn't provide any localization out-of-the-box and uses "You are not authorized to perform this action" as the default message.
You can add your app-level default fallback by providing the action_policy.unauthorized
key value.
When using Rails, all you need is to add translations to any file under the config/locales
folder (or create a new file, e.g. config/locales/policies.yml
).
Non-Rails projets should configure i18n
gem manually:
I18n.load_path << Dir[File.expand_path("config/locales") + "/*.yml"]
ActionPolicy
uses the action_policy
scope. Specific policies translations must be stored inside the policy
sub-scope.
The following algorithm is used to find out the translation for a policy with a class klass
and rule rule
:
- Translation for
"#{klass.identifier}.#{rule}"
key, whenself.identifier =
is not specified then underscored class name without the Policy suffix would be used (e.g.GuestUserPolicy
turns intoguest_user:
scope) - Repeat step 1 for each ancestor which looks like a policy (
.respond_to?(:identifier)?
) up toActionPolicy::Base
- Use
#{rule}
key - Use
en.action_policy.unauthorized
key - Use a default message provided by the gem
For example, given a GuestUserPolicy
class which is inherited from DefaultUserPolicy
and a rule feed?
, the following list of possible translation keys would be used: [:"action_policy.policy.guest_user.feed?", :"action_policy.policy.default_user.feed?", :"action_policy.policy.feed?", :"action_policy.unauthorized"]