-
-
Notifications
You must be signed in to change notification settings - Fork 90
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
I18n integration #15
Comments
Hi @palkan, would you like help with this implementation? Currently I'm hacking it like:
What are your ideas around how you'd implement this in the gem? :) |
An extra consideration around namespaces could be that we first try the namespaced policy in the key, then (if missing) start stripping namespaces off and retrying until there are none so that one doesn't have to repeat data in the translation file. |
Hi @brendon!
The idea is the following. First, add a general helper method, say, def full_message(policy_class, rule)
# generate candidates
candidates = [:"policy.#{policy_class.identifier}.#{rule}"]
# then we have to populate candidates taking into account superclasses
# and probably namespaces
candidates << ...
# then add global fallbacks
candidates << :"policy.#{rule}" # e.g. "action_policy.policy.index?"
candidates << :default_message
I18n.t(
candidates.shift,
default: candidates,
scope: [:action_policy]
)
end
Having this we can easily extend ActionPolicy::Unauthorized.include(Module.new do
def message
ActionPolicy::I18n.full_message(policy, rule)
end
end)
ActionPolicy::Policy::FailureReasons.include(Module.new do
def full_messages
reasons.flat_map do |policy_klass, rules|
rules.map { |rule| ActionPolicy::I18n.full_message(policy_klass, rules) }
end
end
end) The trickiest part here is generating lookup candidates. We should take into account parent policy classes. For example: # having such policies
class UserPolicy < ActionPolicy::Base
def index?; end
end
class GuestPolicy < UserPolicy; end
class Admin::UserPolicy < UserPolicy; end
class Admin::GuestPolicy < Admin::UserPolicy; end
# the lookup candidates should be
# for UserPolicy
["user.index?"]
# for GuestPolicy
["guest.index?", "user.index?"]
# for Admin::UserPolicy
["admin/user.index?", "user.index?"]
# for Admin::GuestPolicy
["admin/guest.index?", "admin/user.index?", "guest.index?", "user.index?"] |
Thanks @palkan :) If I get some spare time I'll have a go at this :) |
Note to myself: Add to docs the following instructions on how to configure Rails to store locale files in # in config/application.rb
config.i18n.load_path += Dir[
Rails.root.join('config', 'locales', '**', '*.{yml,rb}').to_s
] |
I've added a basic implementation to my project: https://gist.github.com/palkan/eb6fab36c5f60e899cccacd3d5649a93 Works good; no complex lookup strategies yet. |
Well done :) |
In locales:
The text was updated successfully, but these errors were encountered: