Using cancancan and packwerk for defining ability file: Seeking insights and alternative approaches

This message was imported from the Ruby/Rails Modularity Slack server. Find more info in the import thread.

Message originally sent by slack user U70I61FD0VD

Is anyone using cancancan and packwerk? If so, what approach have you taken to defining the ability file? I’m leaning towards an approach where each pack defines the rules and registers them with (or is called from) the main ability file, but would love some real world insights / alternatives

Yes — this is exactly what we do!

here’s a micro-example:

# packs/my_pack/config/initializers/authorizations.rb
Rails.application.config.to_prepare do
  Security::Authorizations.register_admin_ability do
    subject(MyThingToBeAuthorized, owner: { id: params(:company_id) }) do
      can [:show], with: SomePermissionConstant
      can_query_fields [:id, :status, :uuid], with: OtherPermissionConstant
    end
  end
end

The to_prepare there is so that these don’t rerun on code reload AND so that these run once after the application boots so we have access to autoloaded constants

Actually works pretty great so far!

Message originally sent by slack user U70I61FD0VD

awesome, thanks! Great tip with using to_prepare there :bow: