Skip to content

Latest commit

 

History

History
44 lines (29 loc) · 2.29 KB

i18n.md

File metadata and controls

44 lines (29 loc) · 2.29 KB

I18n Support

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.

Configuration

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"]

Translations lookup

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:

  1. Translation for "#{klass.identifier}.#{rule}" key, when self.identifier = is not specified then underscored class name without the Policy suffix would be used (e.g. GuestUserPolicy turns into guest_user: scope)
  2. Repeat step 1 for each ancestor which looks like a policy (.respond_to?(:identifier)?) up to ActionPolicy::Base
  3. Use #{rule} key
  4. Use en.action_policy.unauthorized key
  5. 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"]