### Example Usage of Policy Scope - Pundit Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Ascope Demonstrates how to obtain the scope class and then use its `resolve` method to get an active record relation. ```ruby scope = finder.scope #=> UserPolicy::Scope scope.resolve #=> <#ActiveRecord::Relation ...> ``` -------------------------------- ### Initialize PolicyFinder Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Instantiate PolicyFinder with the object for which to find policies. This is the starting point for using the finder. ```ruby user = User.find(params[:id]) finder = PolicyFinder.new(user) ``` ```ruby # File 'lib/pundit/policy_finder.rb', line 29 def initialize(object) @object = object end ``` -------------------------------- ### Get Singleton Instance of NullStore Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore/NullStore.instance Returns the singleton instance of the NullStore. This method is part of the private API and should be used with caution. ```ruby def instance @instance end ``` -------------------------------- ### permissions Source: https://www.rubydoc.info/gems/pundit/Pundit/RSpec/DSL Mixed in to all policy example groups to provide a DSL for defining and testing permissions. It allows you to group tests by permission and optionally focus on specific permission tests. ```APIDOC ## permissions(*list, &block) ### Description This method is mixed in to all policy example groups to provide a DSL for defining and testing permissions. It allows you to group tests by permission and optionally focus on specific permission tests. ### Method `permissions` ### Parameters * `list` (`Symbol`, `Array`) - A permission symbol or an array of permission symbols to describe. The last symbol can be `:focus` to mark the example group for focused execution. * `&block` - A block of RSpec examples to be executed within the context of the specified permissions. ### Request Example ```ruby describe PostPolicy do permissions :show?, :update? do it { is_expected.to permit(user, own_post) } end end ``` ##### Focused Example Group ```ruby describe PostPolicy do permissions :show?, :update?, :focus do it { is_expected.to permit(user, own_post) } end end ``` ### Response This method does not return a value; it configures the RSpec example group. ``` -------------------------------- ### Retrieve Policy or Raise Error Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy%21 Use this method to get the policy for a record. It will raise `NotDefinedError` or `InvalidConstructorError` if the policy cannot be found or constructed. ```ruby def policy!(record) cached_find(record, &:policy!) end ``` -------------------------------- ### Define Policy Permissions in RSpec Source: https://www.rubydoc.info/gems/pundit/Pundit/RSpec/DSL Use the `permissions` method to define and group authorization checks for a policy. It accepts a list of permission symbols and an optional block for RSpec examples. The `:focus` symbol can be appended to a permission to focus the example group. ```ruby describe PostPolicy do permissions :show?, :update? do it { is_expected.to permit(user, own_post) } end end ``` ```ruby describe PostPolicy do permissions :show?, :update?, :focus do it { is_expected.to permit(user, own_post) } end end ``` -------------------------------- ### Copy Application Policy - Pundit Generator Source: https://www.rubydoc.info/gems/pundit/Pundit/Generators/InstallGenerator%3Acopy_application_policy Generates the application policy file using a template. This method is part of the Pundit installation generator. ```ruby def copy_application_policy template "application_policy.rb.tt", "app/policies/application_policy.rb" end ``` -------------------------------- ### Get Object Param Key Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Determine the parameter key for the object, which is useful when working with Rails parameters. Handles arrays and class objects. ```ruby # File 'lib/pundit/policy_finder.rb', line 76 def param_key # rubocop:disable Metrics/AbcSize model = object.is_a?(Array) ? object.last : object if model.respond_to?(:model_name) model.model_name.param_key.to_s elsif model.is_a?(Class) model.to_s.demodulize.underscore else model.class.to_s.demodulize.underscore end end ``` -------------------------------- ### Get Policy Scope (with error handling) Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Retrieves the policy scope class, raising an error if it cannot be determined. Use this when a scope is strictly required and its absence indicates a configuration problem. ```ruby # File 'lib/pundit/policy_finder.rb', line 61 def scope! scope or raise NotDefinedError, "unable to find scope `#{find(object)}::Scope` for `#{object.inspect}`" end ``` -------------------------------- ### Get Policy Scope Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Retrieves the policy scope class. This is useful for understanding how policies are organized and for potential custom scope implementations. ```ruby scope = finder.scope #=> UserPolicy::Scope scope.resolve #=> <#ActiveRecord::Relation ...> ``` ```ruby # File 'lib/pundit/policy_finder.rb', line 40 def scope "#{policy}::Scope".safe_constantize end ``` -------------------------------- ### Pundit::RSpec::Matchers.description Method Source: https://www.rubydoc.info/gems/pundit/Pundit/RSpec/Matchers.description This private method is used internally by the Pundit `permit` matcher to get a description for authorization checks. It can be configured with a callable object to provide custom descriptions. ```ruby def description(user, record) return @description.call(user, record) if defined?(@description) && @description.respond_to?(:call) @description end ``` -------------------------------- ### Get User from Pundit Context Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Auser This method is used to retrieve the user object associated with the current authorization context. It is a readonly attribute. ```Ruby def user @user end ``` -------------------------------- ### Retrieve Policy Scope with Error Handling Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy_scope%21 Use this method to get the policy scope for an object. It raises `NotDefinedError` if the scope is not found or `InvalidConstructorError` if the policy constructor is incorrect. Ensure the `user` and `pundit_model` are correctly set up. ```ruby def policy_scope!(scope) policy_scope_class = policy_finder(scope).scope! begin policy_scope = policy_scope_class.new(user, pundit_model(scope)) rescue ArgumentError raise InvalidConstructorError, "Invalid #<#{policy_scope_class}> constructor is called" end policy_scope.resolve end ``` -------------------------------- ### Get Policy Class with Pundit::PolicyFinder#policy Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Apolicy Returns the policy class associated with an object. Use this when you need to determine the policy class before performing authorization checks. ```ruby policy = finder.policy #=> UserPolicy policy.show? #=> true policy.update? #=> false ``` ```ruby def policy klass = find(object) klass.is_a?(String) ? klass.safe_constantize : klass end ``` -------------------------------- ### Get Scope Class with Pundit::PolicyFinder#scope! Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Ascope%21 Use this method to retrieve the scope class associated with an object. It raises `NotDefinedError` if the scope cannot be determined. ```ruby def scope! scope or raise NotDefinedError, "unable to find scope `#{find(object)}::Scope` for `#{object.inspect}`" end ``` -------------------------------- ### Pundit::Context#policy Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy Retrieves the policy for the given record. This method is used to get an instance of the policy class that can be used to perform query methods. ```APIDOC ## Pundit::Context#policy(record) ### Description Retrieves the policy for the given record. ### Parameters #### Path Parameters * **record** (Object) - The object we're retrieving the policy for. ### Returns * (Object, nil) - An instance of the policy class with query methods. ### Raises * (InvalidConstructorError) - If the policy constructor is called incorrectly. ### See Also * https://github.com/varvet/pundit#policies ### Since * v2.3.2 ``` -------------------------------- ### Get Object's Param Key - Pundit::PolicyFinder Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Aparam_key Returns the name of the key this object would have in a params hash. Handles arrays, classes, and other objects by inferring the key from their model name or class name. ```ruby def param_key # rubocop:disable Metrics/AbcSize model = object.is_a?(Array) ? object.last : object if model.respond_to?(:model_name) model.model_name.param_key.to_s elsif model.is_a?(Class) model.to_s.demodulize.underscore else model.class.to_s.demodulize.underscore end end ``` -------------------------------- ### Get Policy Scope Class - Pundit Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Ascope Use this method to retrieve the associated scope class for a policy. It dynamically constructs the scope class name based on the policy name and attempts to constantize it. ```ruby def scope "#{policy}::Scope".safe_constantize end ``` -------------------------------- ### Pundit::Context#policy_scope! Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy_scope%21 Retrieves the policy scope for the given record. Raises if not found. This method is used to get an instance of the scope class, which can then be used to resolve the scope. It handles potential errors like the policy scope not being defined or the constructor being called incorrectly. ```APIDOC ## Pundit::Context#policy_scope! ### Description Retrieves the policy scope for the given record. Raises if not found. ### Method `policy_scope!(scope)` ### Parameters #### Path Parameters - **scope** (Object) - The object for which to retrieve the policy scope. ### Returns - **Scope{#resolve}** - An instance of the scope class which can resolve to a scope. ### Raises - **NotDefinedError** - If the policy scope cannot be found. - **InvalidConstructorError** - If the policy constructor is called incorrectly. ### See Also - https://github.com/varvet/pundit#scopes ### Since - v2.3.2 ``` -------------------------------- ### LegacyStore#initialize Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore/LegacyStore Initializes a new instance of LegacyStore. This is a private method and should be used with caution. ```APIDOC ## initialize(hash = {}) ### Description Returns a new instance of LegacyStore. ### Method constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **hash** (Hash) - Optional - A hash to initialize the store with. ### Request Example ```ruby LegacyStore.new({ some_key: 'some_value' }) ``` ### Response #### Success Response (200) * **LegacyStore** - A new instance of LegacyStore. ### Response Example ```ruby # ``` ``` -------------------------------- ### Initialize LegacyStore Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore/LegacyStore%3Ainitialize Initializes a new instance of LegacyStore. This method is part of a private API and should be avoided if possible. ```ruby def initialize(hash = {}) @store = hash end ``` -------------------------------- ### PolicyFinder#initialize Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Initializes a new PolicyFinder instance with the object for which policies will be found. ```APIDOC ## initialize(object) ### Description Returns a new instance of PolicyFinder. ### Parameters #### object - **object** (any) - Required - The object to find policy and scope classes for. ### Returns - **PolicyFinder** - A new instance of PolicyFinder. ### Since - v0.1.0 ``` -------------------------------- ### Pundit::Context#initialize Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Ainitialize Initializes a new instance of Context, which holds the user and a cache store for policies. ```APIDOC ## initialize(user:, policy_cache: CacheStore::NullStore.instance) ### Description Returns a new instance of Context. ### Parameters #### Path Parameters - **user** - (type: unspecified) - later passed to policies and scopes - **policy_cache** (type: CacheStore::NullStore.instance) - Optional - cache store for policies (see e.g. Pundit::CacheStore::NullStore) ### Method initialize ### Endpoint N/A (Method Signature) ### Request Example ```ruby Pundit::Context.new(user: current_user) ``` ### Response #### Success Response - **Context** - A new instance of the Context class. ``` -------------------------------- ### Pundit::PolicyFinder#initialize Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Ainitialize Initializes a new instance of PolicyFinder. This method takes an object and prepares the finder to locate its associated policy and scope classes. ```APIDOC ## Pundit::PolicyFinder#initialize ### Description Returns a new instance of PolicyFinder. ### Method initialize ### Parameters #### Path Parameters - **object** (any) - The object to find policy and scope classes for. ### Request Example ```ruby PolicyFinder.new(user) ``` ### Response #### Success Response (PolicyFinder) - Returns a new instance of PolicyFinder. ### Since v0.1.0 ``` -------------------------------- ### Initialize PolicyFinder Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Ainitialize Initializes a new PolicyFinder instance with the object to find policies for. This is the primary way to create a PolicyFinder. ```ruby def initialize(object) @object = object end ``` -------------------------------- ### Initialize Pundit::Context Constructor Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Initializes a new Pundit::Context instance. It requires a user and optionally accepts a policy cache store. Defaults to NullStore if no cache is provided. ```ruby # File 'lib/pundit/context.rb', line 35 def initialize(user:, policy_cache: CacheStore::NullStore.instance) @user = user @policy_cache = policy_cache end ``` -------------------------------- ### Cache Store Interface: Fetch Method Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore This method is a template for looking up a stored policy or generating a new one if it's not found. It accepts user, record, and a block for generation. Note that this method itself does not exist in the module but serves as an interface definition. ```Ruby def fetch(user:, record:, &block) end ``` -------------------------------- ### NullStore.instance Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore/NullStore.instance Returns the singleton instance of the NullStore. This method is part of a private API and should be used with caution. ```APIDOC ## NullStore.instance ### Description Returns the singleton instance of the NullStore. ### Method `instance` ### Returns * (`NullStore`) - the singleton instance ``` -------------------------------- ### Pundit::CacheStore::NullStore#fetch Implementation Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore/NullStore%3Afetch This method always yields, bypassing any caching logic. It is part of the private API and should be used with caution. ```ruby def fetch(*, **) yield end ``` -------------------------------- ### Pundit::CacheStore#fetch Method Signature Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore%3Afetch This is the method signature for `fetch` in `Pundit::CacheStore`. It's a template and the method itself is not implemented in this module. It's used to look up or generate a policy. ```ruby def fetch(user:, record:, &block) ``` -------------------------------- ### Pundit::CacheStore::NullStore#fetch Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore/NullStore%3Afetch This method is part of a private API and should be avoided. It always yields and does not cache anything, returning whatever the block returns. ```APIDOC ## Pundit::CacheStore::NullStore#fetch ### Description Always yields, does not cache anything. ### Method `fetch(*, **)` ### Parameters This method accepts arbitrary positional and keyword arguments, which are ignored. ### Yields * The block passed to the method. ### Returns * `any` - Whatever the block returns. ### Since * v2.3.2 ### Example ```ruby Pundit::CacheStore::NullStore.new.fetch do # Some operation 'result' end # => 'result' ``` ``` -------------------------------- ### Authorize Action with Pundit::Context Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Aauthorize Use this method to authorize an action on a record. It finds the appropriate policy, initializes it, and checks the specified query. Raises NotAuthorizedError if authorization fails. ```ruby def authorize(possibly_namespaced_record, query:, policy_class:) record = pundit_model(possibly_namespaced_record) policy = if policy_class policy_class.new(user, record) else policy!(possibly_namespaced_record) end raise NotAuthorizedError, query: query, record: record, policy: policy unless policy.public_send(query) record end ``` -------------------------------- ### Pundit::Context#authorize Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Retrieves the policy for a given record, initializes it with the record and user, and throws an error if the user is not authorized. ```APIDOC ## authorize(possibly_namespaced_record, query:, policy_class:) ### Description Retrieves the policy for the given record, initializing it with the record and user and finally throwing an error if the user is not authorized to perform the given action. ### Parameters * possibly_namespaced_record (Object, Array) - The object we're checking permissions of. * query (Symbol, String) - The predicate method to check on the policy (e.g., `:show?`). * policy_class (Class) - The policy class we want to force use of. ### Returns * Object - Always returns the passed object record. ### Raises * Pundit::NotAuthorizedError - If the given query method returned false. ### Since * v2.3.2 ``` -------------------------------- ### Initialize Pundit Context Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Ainitialize Initializes a new Pundit Context object. It requires a user and optionally accepts a policy cache. The default policy cache is Pundit::CacheStore::NullStore.instance. ```ruby def initialize(user:, policy_cache: CacheStore::NullStore.instance) @user = user @policy_cache = policy_cache end ``` -------------------------------- ### Create Policy File Source: https://www.rubydoc.info/gems/pundit/Pundit/Generators/PolicyGenerator Generates a new policy file using a template. This method is part of the Rails generator system for Pundit. ```ruby def create_policy template "policy.rb.tt", File.join("app/policies", class_path, "#{file_name}_policy.rb") end ``` -------------------------------- ### Initialize Pundit Context in Sinatra Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Set up a helper method to create a Pundit::Context instance using the current user. This context is then used for authorization checks within Sinatra routes. ```ruby helpers do def current_user = ... def pundit @pundit ||= Pundit::Context.new(user: current_user) end end get "/posts/:id" do |id| pundit.authorize(Post.find(id), query: :show?) end ``` -------------------------------- ### Pundit::CacheStore#fetch Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore%3Afetch Looks up a stored policy or generates a new one. This method is a template and does not exist in the current implementation. ```APIDOC ## Pundit::CacheStore#fetch ### Description Looks up a stored policy or generates a new one. This method is a template and does not exist in the current implementation. ### Method fetch ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * user (Object) - Optional - the user that initiated the action * record (Object) - Optional - the object being accessed * block (Proc) - Required - the block to execute if missing ### Request Example ```ruby Pundit::CacheStore.fetch(user: user, record: record) do # block to execute if missing end ``` ### Response #### Success Response (200) * Object - the policy #### Response Example ```json { "policy": "some_policy_object" } ``` ``` -------------------------------- ### LegacyStore#fetch Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore/LegacyStore Fetches a value from the cache. If the value is not found, it yields a block to compute and cache the value. This is a private method. ```APIDOC ## fetch(user:, record:) ### Description A cache store that uses only the record as a cache key, and ignores the user. `nil` results are not cached. ### Method private ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **user** (Object) - Required - The user object (ignored by this cache store). * **record** (Object) - Required - The record object to use as the cache key. ### Request Example ```ruby cache_store.fetch(user: current_user, record: @post) do # Compute and return the cached value @post.calculate_something end ``` ### Response #### Success Response (200) * **Object** - The cached value or the result of the yielded block. ### Response Example ```ruby # The cached value or the computed result ``` ``` -------------------------------- ### Pundit::Context#authorize Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Aauthorize Retrieves the policy for a given record, initializes it with the record and user, and raises an error if the user is not authorized to perform the specified query. It can optionally force the use of a specific policy class. ```APIDOC ## authorize(possibly_namespaced_record, query:, policy_class:) ⇒ Object ### Description Retrieves the policy for the given record, initializing it with the record and user and finally throwing an error if the user is not authorized to perform the given action. ### Method authorize ### Parameters #### Path Parameters - **possibly_namespaced_record** (Object, Array) - The object we're checking permissions of. - **query** (Symbol, String) - The predicate method to check on the policy (e.g. `:show?`). - **policy_class** (Class) - The policy class we want to force use of. ### Returns - **Object** - Always returns the passed object record. ### Raises - **NotAuthorizedError** - if the given query method returned false ### Since - v2.3.2 ``` -------------------------------- ### Initialize NotAuthorizedError with Options Source: https://www.rubydoc.info/gems/pundit/Pundit/NotAuthorizedError%3Ainitialize Use this overload to create an error with detailed information about the authorization failure. It accepts an options hash that can include a custom message, the policy method name, the record being checked, and the policy class. ```ruby def initialize(options = {}) if options.is_a? String message = options else @query = options[:query] @record = options[:record] @policy = options[:policy] message = options.fetch(:message) do record_name = record.is_a?(Class) ? record.to_s : "this #{record.class}" "not allowed to #{policy.class}##{query} #{record_name}" end end super(message) end ``` -------------------------------- ### Cache Store Interface Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore The Cache Store Interface defines the contract for cache store implementations, including the `fetch` method. ```APIDOC ## fetch(user:, record:, &block) ### Description Looks up a stored policy or generates a new one. ### Method fetch ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```ruby # Example usage (conceptual, as this is a template) cache_store.fetch(user: current_user, record: post) do Policy.new(current_user, post) end ``` ### Response #### Success Response (200) - **policy** (Object) - The policy instance, either fetched or newly generated. #### Response Example ```json { "policy": "" } ``` ``` -------------------------------- ### Initialize Pundit Context in Roda Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Create a Pundit::Context instance within a Roda route block. This context is then used to authorize actions on specific records. ```ruby route do |r| context = Pundit::Context.new(user:) r.get "posts", Integer do |id| context.authorize(Post.find(id), query: :show?) end end ``` -------------------------------- ### Generate Policy Test - TestUnit Source: https://www.rubydoc.info/gems/pundit/TestUnit/Generators/PolicyGenerator Use this method to generate a new policy test file for TestUnit. It utilizes a template to create the test structure. ```ruby def create_policy_test template "policy_test.rb.tt", File.join("test/policies", class_path, "#{file_name}_policy_test.rb") end ``` -------------------------------- ### Create Policy Spec - Rspec Generator Source: https://www.rubydoc.info/gems/pundit/Rspec/Generators/PolicyGenerator Use this method to generate a new RSpec policy specification file. It utilizes a template to create the spec file in the correct directory. ```ruby def create_policy_spec template "policy_spec.rb.tt", File.join("spec/policies", class_path, "#{file_name}_policy_spec.rb") end ``` -------------------------------- ### PolicyFinder#param_key Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Determines the key name for the object as it would appear in a params hash. ```APIDOC ## param_key ### Description Returns the name of the key this object would have in a params hash. ### Returns - **String** - The name of the key this object would have in a params hash. ### Since - v1.1.0 ``` -------------------------------- ### Pundit RSpec DSL Permissions Implementation Source: https://www.rubydoc.info/gems/pundit/Pundit/RSpec/DSL%3Apermissions The core implementation of the `permissions` method in Pundit's RSpec DSL. It handles metadata and creates a described group for the permissions. ```ruby def permissions(*list, &block) metadata = { permissions: list, caller: caller } if list.last == :focus list.pop metadata[:focus] = true end description = list.to_sentence describe(description, metadata) { instance_eval(&block) } end ``` -------------------------------- ### Pundit::NotAuthorizedError#initialize Source: https://www.rubydoc.info/gems/pundit/Pundit/NotAuthorizedError%3Ainitialize Initializes a new instance of NotAuthorizedError. It can be initialized with a simple string message or with an options hash for more detailed error information. ```APIDOC ## initialize(message) ### Description Create an error with a simple error message. ### Parameters * **message** (String) - A simple error message string. ## initialize(options) ### Description Create an error with the specified attributes. ### Parameters * **options** (Hash) - The error options. * **:message** (String) - Optional custom error message. Will default to a generalized message. * **:query** (Symbol) - The name of the policy method that was checked. * **:record** (Object) - The object that was being checked with the policy. * **:policy** (Class) - The class of policy that was used for the check. ### Returns * NotAuthorizedError - A new instance of NotAuthorizedError. ``` -------------------------------- ### Define Pundit.policy_scope! Method Source: https://www.rubydoc.info/gems/pundit/Pundit.policy_scope%21 This method is used to create a new Pundit context and call the policy_scope! method on it. It accepts a user object and any additional arguments or blocks to pass to the context's policy_scope! method. ```Ruby def policy_scope!(user, *args, **kwargs, &block) Context.new(user: user).policy_scope!(*args, **kwargs, &block) end ``` -------------------------------- ### Include Pundit RSpec DSL and Metadata Source: https://www.rubydoc.info/gems/pundit/Pundit/RSpec/PolicyExampleGroup.included This method is called when the `PolicyExampleGroup` module is included in a class. It sets the metadata type to `:policy` and extends the base class with Pundit's RSpec DSL. ```ruby def self.included(base) base.metadata[:type] = :policy base.extend Pundit::RSpec::DSL super end ``` -------------------------------- ### Find Policy Class (with error) Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Retrieve the policy class for the given object, raising a NotDefinedError if the policy cannot be determined. Use this when a policy is expected to exist. ```ruby # File 'lib/pundit/policy_finder.rb', line 69 def policy! policy or raise NotDefinedError, "unable to find policy `#{find(object)}` for `#{object.inspect}`" end ``` -------------------------------- ### Fetch data from cache or compute Source: https://www.rubydoc.info/gems/pundit/Pundit/CacheStore/LegacyStore%3Afetch Use this method to retrieve cached data for a given record. If the data is not found in the cache, it will be computed using the provided block. Note that nil results are not cached. ```ruby def fetch(user:, record:) _ = user @store[record] ||= yield end ``` -------------------------------- ### Pundit::PolicyFinder#param_key Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Aparam_key Returns the name of the key this object would have in a params hash. ```APIDOC ## Pundit::PolicyFinder#param_key ### Description Returns the name of the key this object would have in a params hash. ### Method `param_key` ### Returns * `String` - The name of the key this object would have in a params hash. ### Since * v1.1.0 ### Source Code ```ruby def param_key model = object.is_a?(Array) ? object.last : object if model.respond_to?(:model_name) model.model_name.param_key.to_s elsif model.is_a?(Class) model.to_s.demodulize.underscore else model.class.to_s.demodulize.underscore end end ``` ``` -------------------------------- ### Find Policy Class with Error Handling Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Apolicy%21 Use this method to find the policy class for an object. It raises a NotDefinedError if the policy cannot be determined, providing details about the object and the attempted policy lookup. ```ruby def policy! policy or raise NotDefinedError, "unable to find policy `#{find(object)}` for `#{object.inspect}`" end ``` -------------------------------- ### Focus Permissions in RSpec Source: https://www.rubydoc.info/gems/pundit/Pundit/RSpec/DSL%3Apermissions Use the `:focus` keyword to run only the tests within this specific permissions block during RSpec execution. ```ruby describe PostPolicy do permissions :show?, :update?, :focus do it { is_expected.to permit(user, own_post) } end end ``` -------------------------------- ### Pundit::Context#policy_scope Implementation Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy_scope Retrieves the policy scope for a given record. It finds the appropriate policy scope class, instantiates it with the user and scope, and then calls the resolve method. Raises InvalidConstructorError if the policy scope class constructor is invalid. ```ruby def policy_scope(scope) policy_scope_class = policy_finder(scope).scope return unless policy_scope_class begin policy_scope = policy_scope_class.new(user, pundit_model(scope)) rescue ArgumentError raise InvalidConstructorError, "Invalid #<#{policy_scope_class}> constructor is called" end policy_scope.resolve end ``` -------------------------------- ### authorize Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Authorizes an action for a given record. It checks if the user is authorized to perform the specified query on the record using its associated policy. ```APIDOC ## authorize(possibly_namespaced_record, query:, policy_class:) ### Description Authorizes an action for a given record. It checks if the user is authorized to perform the specified query on the record using its associated policy. ### Parameters #### Path Parameters - **possibly_namespaced_record** (Object) - The record to authorize. - **query** (String) - The query to perform on the policy. - **policy_class** (Class, optional) - The specific policy class to use. ### Raises - **NotAuthorizedError**: If the user is not authorized to perform the query. ``` -------------------------------- ### PolicyFinder#object Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Retrieves the object associated with this PolicyFinder instance. ```APIDOC ## object ### Description Retrieves the object associated with this PolicyFinder instance. ### Returns - **Object** - The object for which policies are being found. ### Since - v0.1.0 ``` -------------------------------- ### PolicyFinder#policy! Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Finds and returns the policy class associated with the object, raising an error if not found. ```APIDOC ## policy! ### Description Finds and returns the policy class associated with the object. This method will raise an error if the policy cannot be determined. ### Returns - **Class** - The policy class. ### Raises - **NotDefinedError** - If the policy could not be determined. ### Since - v0.1.0 ``` -------------------------------- ### Define Permissions in RSpec Source: https://www.rubydoc.info/gems/pundit/Pundit/RSpec/DSL%3Apermissions Use this to define a block of tests for specific permissions. It groups tests related to the listed permissions. ```ruby describe PostPolicy do permissions :show?, :update? do it { is_expected.to permit(user, own_post) } end end ``` -------------------------------- ### Retrieve Policy for a Record - Ruby Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy Retrieves the policy for a given record. Raises InvalidConstructorError if the policy constructor is called incorrectly. See Also: https://github.com/varvet/pundit#policies ```ruby def policy(record) cached_find(record, &:policy) end ``` -------------------------------- ### Include Pundit Authorization in Controllers Source: https://www.rubydoc.info/gems/pundit/Pundit/Authorization Include this module in your ApplicationController to provide authorization helpers throughout your application. This is the standard way to integrate Pundit. ```ruby class ApplicationController < ActionController::Base include Pundit::Authorization end ``` -------------------------------- ### Pundit::RSpec::DSL#permissions Source: https://www.rubydoc.info/gems/pundit/Pundit/RSpec/DSL%3Apermissions The `permissions` method is used to group authorization tests for specific actions. It accepts a list of actions (as symbols) and an optional `:focus` keyword. A block is yielded to define the individual test cases for these permissions. ```APIDOC ## Pundit::RSpec::DSL#permissions ### Description Defines a block of tests for a given set of permissions. Accepts a list of permission symbols and an optional `:focus` keyword. The block passed to `permissions` is evaluated in the context of the policy example group. ### Method Signature `permissions(*list, &block)` ### Parameters - `*list` (Array) - A list of symbols representing the actions to test, optionally ending with `:focus` to focus the example group. - `&block` (Proc) - A block containing the RSpec examples for the specified permissions. ### Returns `void` - This method does not return a value; it defines an RSpec example group. ### Examples #### Basic Usage ```ruby describe PostPolicy do permissions :show?, :update? do it { is_expected.to permit(user, own_post) } end end ``` #### Focused Example Group ```ruby describe PostPolicy do permissions :show?, :update?, :focus do it { is_expected.to permit(user, own_post) } end end ``` ### Since v0.1.0 ``` -------------------------------- ### policy! Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Retrieves the policy for the given record, raising an error if it cannot be found. This method is similar to `policy` but ensures a policy is always returned or an error is raised. ```APIDOC ## policy!(record) ### Description Retrieves the policy for the given record, raising an error if it cannot be found. This method is similar to `policy` but ensures a policy is always returned or an error is raised. ### Parameters #### Path Parameters - **record** (Object) - The object for which to retrieve the policy. ### Returns - **Object**: An instance of the policy class with query methods. ### Raises - **NotDefinedError**: If the policy cannot be found. - **InvalidConstructorError**: If the policy constructor is called incorrectly. ``` -------------------------------- ### scope! Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Retrieves the policy scope class and raises an error if it cannot be determined. This method is a stricter version of `scope`. ```APIDOC ## scope! ### Description Retrieves the policy scope class and raises an error if it cannot be determined. This method is a stricter version of `scope`. ### Method `scope!` ### Returns * (`Scope{#resolve}`) — scope class which can resolve to a scope ### Raises * (`NotDefinedError`) — if scope could not be determined ``` -------------------------------- ### Authorize Action with Pundit::Context Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Checks if the user is authorized to perform a specific query on a record. Throws NotAuthorizedError if the action is not permitted. The policy class can be explicitly specified. ```ruby # File 'lib/pundit/context.rb', line 62 def authorize(possibly_namespaced_record, query:, policy_class:) # ... implementation details ... end ``` -------------------------------- ### Pundit::Context#policy! Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy%21 Retrieves the policy for the given record, or raises an error if not found. This method is useful for ensuring a policy exists before performing an action. ```APIDOC ## Pundit::Context#policy! ### Description Retrieves the policy for the given record, or raises if not found. ### Method `policy!(record)` ### Parameters #### Path Parameters - **record** (Object) - Required - The object we're retrieving the policy for. ### Returns - **Object** - An instance of the policy class with query methods. ### Raises - **NotDefinedError** - If the policy cannot be found. - **InvalidConstructorError** - If the policy constructor is called incorrectly. ### See Also - https://github.com/varvet/pundit#policies ### Since - v2.3.2 ``` -------------------------------- ### PolicyFinder#policy Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Finds and returns the policy class associated with the object. ```APIDOC ## policy ### Description Finds and returns the policy class associated with the object. If the policy class cannot be determined, it returns nil. ### Examples ```ruby policy = finder.policy #=> UserPolicy policy.show? #=> true policy.update? #=> false ``` ### Returns - **nil, Class** - The policy class or nil if not found. ### See Also - https://github.com/varvet/pundit#policies ### Since - v0.1.0 ``` -------------------------------- ### Pundit::Helper#policy_scope Source: https://www.rubydoc.info/gems/pundit/Pundit/Helper%3Apolicy_scope This private method delegates to pundit_policy_scope. It is part of the internal implementation and should be avoided by users. ```ruby def policy_scope(scope) pundit_policy_scope(scope) end ``` -------------------------------- ### policy Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Retrieves the policy for the given record. This method caches the policy instance for efficiency. ```APIDOC ## policy(record) ### Description Retrieves the policy for the given record. This method caches the policy instance for efficiency. ### Parameters #### Path Parameters - **record** (Object) - The object for which to retrieve the policy. ### Returns - **Object**: An instance of the policy class with query methods. ### Raises - **InvalidConstructorError**: If the policy constructor is called incorrectly. ``` -------------------------------- ### Find Scope Class (with error) Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Retrieve the scope class for the given object, raising an error if the scope cannot be determined. Use this when a scope is expected to exist. ```ruby finder.scope! #=> UserPolicy::Scope ``` -------------------------------- ### Pundit::Context#policy_scope Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy_scope Retrieves the policy scope for the given record. It finds the appropriate policy scope class, instantiates it with the user and the model, and then resolves the scope. Raises `InvalidConstructorError` if the policy constructor is called incorrectly. ```APIDOC ## Pundit::Context#policy_scope ### Description Retrieves the policy scope for the given record. ### Method `policy_scope(scope)` ### Parameters #### Path Parameters - **scope** (Object) - The record for which to retrieve the policy scope. ### Raises - **InvalidConstructorError**: If the policy constructor is called incorrectly. ### See Also - https://github.com/varvet/pundit#scopes ### Since - v2.3.2 ``` -------------------------------- ### Accessing the Policy Cache in Pundit Context Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Apolicy_cache This method retrieves the cached policies for the current context. It is a private API method and should be avoided in favor of public interfaces. ```ruby def policy_cache @policy_cache end ``` -------------------------------- ### Pundit::PolicyFinder#object Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Aobject Retrieves the object associated with the PolicyFinder instance. This is a read-only attribute. ```APIDOC ## Pundit::PolicyFinder#object ### Description Retrieves the object associated with the PolicyFinder instance. This is a read-only attribute. ### Method `object` ### Returns `Object` - The object associated with the policy finder. ### See Also - `#initialize` ### Since - v0.1.0 ``` -------------------------------- ### Find Policy Class Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Retrieve the policy class for the given object. This method returns the class if found, or nil if not. It's useful for checking policy existence before authorization. ```ruby finder.policy #=> UserPolicy ``` ```ruby # File 'lib/pundit/policy_finder.rb', line 52 def policy klass = find(object) klass.is_a?(String) ? klass.safe_constantize : klass end ``` -------------------------------- ### Pundit.policy_scope! Source: https://www.rubydoc.info/gems/pundit/Pundit.policy_scope%21 This method is used to scope a collection of records based on the current user's policies. It delegates to `Pundit::Context#policy_scope!`. ```APIDOC ## Pundit.policy_scope! ### Description This method is used to scope a collection of records based on the current user's policies. It delegates to `Pundit::Context#policy_scope!`. ### Method `policy_scope!(user, *args, **kwargs, &block)` ### Parameters - **user**: The current user object. - **args**: Positional arguments passed to the underlying policy scope method. - **kwargs**: Keyword arguments passed to the underlying policy scope method. - **block**: A block passed to the underlying policy scope method. ### Returns - `Object`: The scoped collection of records. ``` -------------------------------- ### PolicyFinder Object Attribute Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Access the object that was used to initialize the PolicyFinder. This attribute is read-only. ```ruby # File 'lib/pundit/policy_finder.rb', line 25 def object @object end ``` -------------------------------- ### Pundit::PolicyFinder#policy Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Apolicy Returns the policy class associated with an object. It finds the policy class and returns it, or `nil` if not found. ```APIDOC ## Pundit::PolicyFinder#policy ### Description Returns the policy class associated with an object. It finds the policy class and returns it, or `nil` if not found. ### Method `policy` ### Returns `nil`, `Class` - The policy class or nil. ### Examples: ```ruby finder = Pundit::PolicyFinder.new(user) policy = finder.policy #=> UserPolicy policy.show? #=> true policy.update? #=> false ``` ### Source Code ```ruby def policy klass = find(object) klass.is_a?(String) ? klass.safe_constantize : klass end ``` ``` -------------------------------- ### Pundit::PolicyFinder#policy! Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Apolicy%21 Returns the policy class associated with the object. It raises a `NotDefinedError` if a policy cannot be determined. ```APIDOC ## Pundit::PolicyFinder#policy! ### Description Returns the policy class with query methods. Raises `NotDefinedError` if the policy could not be determined. ### Method `policy!` ### Returns `Class` - The policy class. ### Raises * `NotDefinedError` - If a policy cannot be determined for the object. ### Since v0.1.0 ``` -------------------------------- ### Access Pundit Context User Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Retrieves the user associated with the Pundit context. This user is passed to policies and scopes for authorization checks. ```ruby # File 'lib/pundit/context.rb', line 43 def user @user end ``` -------------------------------- ### Access Pundit Context Policy Cache Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Retrieves the policy cache store associated with the Pundit context. This is a private API method. ```ruby # File 'lib/pundit/context.rb', line 48 def policy_cache @policy_cache end ``` -------------------------------- ### policy_scope! Source: https://www.rubydoc.info/gems/pundit/Pundit/Context Retrieves the policy scope for the given record, raising an error if it cannot be found. This method ensures a policy scope is always returned or an error is raised. ```APIDOC ## policy_scope!(scope) ### Description Retrieves the policy scope for the given record, raising an error if it cannot be found. This method ensures a policy scope is always returned or an error is raised. ### Parameters #### Path Parameters - **scope** (Object) - The object for which to retrieve the policy scope. ### Returns - **Scope{#resolve}**: An instance of the scope class which can resolve to a scope. ### Raises - **NotDefinedError**: If the policy scope cannot be found. - **InvalidConstructorError**: If the policy constructor is called incorrectly. ``` -------------------------------- ### Pundit::NotAuthorizedError#query Source: https://www.rubydoc.info/gems/pundit/Pundit/NotAuthorizedError%3Aquery The `query` method returns the object that was being queried when the `NotAuthorizedError` was raised. This is a read-only attribute. ```APIDOC ## Pundit::NotAuthorizedError#query ### Description Returns the query object associated with the authorization error. ### Method `query` ⇒ `Object` (readonly) ### Since v0.2.3 ### Example ```ruby error = Pundit::NotAuthorizedError.new(query: some_object) puts error.query # Output: some_object ``` ``` -------------------------------- ### scope Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder Retrieves the policy scope class. It attempts to find a scope class named `Scope` within the determined policy class. If not found, it returns nil. ```APIDOC ## scope ### Description Retrieves the policy scope class. It attempts to find a scope class named `Scope` within the determined policy class. If not found, it returns nil. ### Method `scope` ### Returns * (`nil`, `Scope{#resolve}`) — scope class which can resolve to a scope ### Examples ```ruby scope = finder.scope #=> UserPolicy::Scope scope.resolve #=> <#ActiveRecord::Relation ...> ``` ``` -------------------------------- ### Accessing the Query Object in NotAuthorizedError Source: https://www.rubydoc.info/gems/pundit/Pundit/NotAuthorizedError%3Aquery Use this method to retrieve the query object that caused the `NotAuthorizedError`. This is useful for debugging authorization failures. ```ruby def query @query end ``` -------------------------------- ### Accessing the unauthorized record in Pundit::NotAuthorizedError Source: https://www.rubydoc.info/gems/pundit/Pundit/NotAuthorizedError%3Arecord Use the `record` method to retrieve the object that failed authorization. This is useful for logging or providing more context in error messages. Available since v0.2.3. ```ruby def record @record end ``` -------------------------------- ### Pundit::PolicyFinder#scope! Source: https://www.rubydoc.info/gems/pundit/Pundit/PolicyFinder%3Ascope%21 Returns the scope class which can resolve to a scope. Raises NotDefinedError if the scope cannot be determined. ```APIDOC ## Pundit::PolicyFinder#scope! ### Description Returns the scope class which can resolve to a scope. ### Method `scope!` ### Returns - `Scope{#resolve}` — scope class which can resolve to a scope ### Raises - `NotDefinedError` — if scope could not be determined ### Since - v0.1.0 ### Source Code ```ruby def scope! scope or raise NotDefinedError, "unable to find scope `#{find(object)}::Scope` for `#{object.inspect}`" end ``` ``` -------------------------------- ### Pundit::Context#user Source: https://www.rubydoc.info/gems/pundit/Pundit/Context%3Auser Retrieves the user object associated with the Pundit context. This is a read-only attribute. ```APIDOC ## Pundit::Context#user ### Description Retrieves the user object associated with the Pundit context. This is a read-only attribute. ### Method GET (Implicit) ### Endpoint N/A (Instance method) ### Parameters None ### Request Example N/A ### Response #### Success Response (Object) - **user** (Object) - The user object associated with the context. ### Response Example ```ruby context.user ``` ```