Skip to content

Commit

Permalink
Add support to translate action (#594)
Browse files Browse the repository at this point in the history
Suport translate action name
  • Loading branch information
ayumu838 committed Mar 15, 2020
1 parent 8cc9d02 commit 84554d6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
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

0 comments on commit 84554d6

Please sign in to comment.