Skip to content
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

Add support to translate action #594

Merged
merged 6 commits into from
Mar 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/cancan/unauthorized_message_resolver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ module CanCan
module UnauthorizedMessageResolver
def unauthorized_message(action, subject)
keys = unauthorized_message_keys(action, subject)
variables = { action: action.to_s }
variables = {}
variables[:action] = I18n.translate("actions.#{action}", default: action.to_s)
variables[:subject] = translate_subject(subject)
message = I18n.translate(keys.shift, **variables.merge(scope: :unauthorized, default: keys + ['']))
message.blank? ? nil : message
Expand Down
21 changes: 21 additions & 0 deletions spec/cancan/ability_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,27 @@ class Account
end
end

it "uses action's name in i18n" do
class Account
include ActiveModel::Model
end

I18n.backend.store_translations :en,
actions: { update: 'english name' },
unauthorized: { update: { all: '%{action}' } }
I18n.backend.store_translations :ja,
actions: { update: 'japanese name' },
unauthorized: { update: { all: '%{action}' } }

I18n.with_locale(:en) do
expect(@ability.unauthorized_message(:update, Account)).to eq('english name')
end

I18n.with_locale(:ja) do
expect(@ability.unauthorized_message(:update, Account)).to eq('japanese name')
end
end

it 'uses symbol as subject directly' do
I18n.backend.store_translations :en, unauthorized: { has: { cheezburger: 'Nom nom nom. I eated it.' } }
expect(@ability.unauthorized_message(:has, :cheezburger)).to eq('Nom nom nom. I eated it.')
Expand Down