Where does CanCanCan define the flash "% {subject}" and how to modify it to be compatible with Rails localization conventions?

CanCanCan displays localized flash messages if the resource is not authorized.

https://github.com/CanCanCommunity/cancancan/wiki/Translations-(i18n)

# en.yml
en:
  unauthorized:
    manage:
      all: "You do not have access to %{action} %{subject}!"

I dug a GitHub repo but can't figure out how a variable is defined subject.

From the conclusion, I would suggest that it subjectis defined as something like object.class.name.underscore.

I want to change this to use object.model_name.human.

This will make it much more compatible with Rails conventions and simplify localization.

en:
  activerecord:
    models:
      mymodel: MyLocalizedSubjectName

Can someone point me to the code that defines it subject, or suggest how I can fix CanCanCan to use localized model names?

+4
4

, unauthorized_message ability.rb. , :

  variables[:subject] = (subject.class == Class ? subject : subject.class).to_s.underscore.humanize.downcase
  message = I18n.translate(keys.shift, variables.merge(scope: :unauthorized, default: keys + ['']))

, , ( humanize).

EDIT: i18n human . :

en:
  activerecord:
    models:
      user: xxxx
      base: aaaa
      activerecord/base: bbbb
      active_record/base: cccc

:

2.4.1 :001 > User.model_name.human
 => "xxxx" 
2.4.1 :002 > ActiveRecord::Base.model_name.human
 => "cccc" 
2.4.1 :003 > 

ActiveRecord::Base.model_name.i18n_key, .

+2

CanCanCan :

authorize! :edit, @widget, message: I18n.t :all, scope: [: unauthorized, :manage], action: :edit, subject: Item

I18n Rails

0

, yml. :

en:
  unauthorized:
    edit:
      widget: "You do not have access to edit item!"

, :

en:
  unauthorized:
    manage:
      widget: "You do not have access to %{action} item!"

, , - to_s Widget:

class Widget
  def self.to_s
    'Item'
  end
end
0

localize path config/locale, , , . , , config/application.rb, :

I18n.available_locales = [:en, :it]
config.i18n.default_locale = :it

, - en.yml, . , : en.yml, it.yml, devise.en.yml devise.it.yml. , , . , :

I18n.locale = :it
I18n.locale = :en

, :

I18n.locale = I18n.default_locale

, ,

0

Source: https://habr.com/ru/post/1682361/


All Articles