An application defines a pundit user according to its context of shop
def pundit_user
CurrentContext.new(current_user, @shop)
end
In practice, the following policy for Contact class
def initialize(user, contact)
@user = user
@contact = contact
end
def create?
user && (user.admin? || user.editor? || (user.id == contact.user_id))
end
does not work as the user attibutes cannot be accessed.
The following error is returned for the admin attribute of user, nor, upon removing the first two conditions, does not access the user's id.
NoMethodError: undefined method `id' for #<CurrentContext:0x0000000114537220
@user=#<User id: 830861402, email: "[email protected]", name_last: "string", name_first: "string", admin: false, editor: false [...] dconne: nil>,
@shop=#<Shop id: 1039309252, name: "[...]
An attempt to alter the initialization invoking the current context
def initialize(current_context, contact)
@user = user
@shop = shop
@contact = contact
end
fails where @shop is not recognized NameError: undefined local variable or method shop' for #<ContactPolicy:`
How can the @user and @shop values be accessed to establish a working policy?
You have to set up
CurrentContextclass so you can use it inside the policy classes:pundit_usermethod is what Pundit uses to initialize a policy class:Inside the policy class, just use
CurrentContextas any other object:To make it obvious what we should get in the initializer, just rename the argument: