0

I have the following hash:

MAPPING = {
   create: [:admin],
   update: [:admin],
   delete: [:admin],
   index: [:all]
}

And I need to create pundit method dynamically in the policy class. I need to search the mapping hash all items that have admin role and create policy methods:

def create?
   true
end

def update?
   true
end

This way I don't have to repeat the code all the time. How can I do this ? Thanks.

2 Answers2

0

The code below defines a method for each key whose value contains :admin. The name of the method is the key, cast to a string, with a question mark appended. Each defined method returns true.

MAPPING.each do |action, roles|
  define_method("#{action}?") do
    true
  end if roles.include?(:admin)
end
hoffm
  • 2,386
  • 23
  • 36
0

This is the code I'm using:

    class CarPolicy < ApplicationPolicy
      attr_reader :user, :record

      def initialize(user, record)
        @user = user
        @record = record
      end

      PERMISSION_KEY_MAPPING = {
        index: [:admin]
      }

      PERMISSION_KEY_MAPPING.each do |action, roles|
        define_method("#{action}?") do
          true
        end if user.roles.include?(:admin)
      end
    end

The line:

end if users.roles.include?(:admin)

Doesn't work because I don't have access to user.roles.