repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/and_node.rb
lib/rubocop/ast/node/and_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `until` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `until` nodes within RuboCop. class AndNode < Node include BinaryOperatorNode include PredicateOperatorNode # Returns the alternate operator of the `and` as a string. # Returns `and` for `&&` and vice versa. # # @return [String] the alternate of the `and` operator def alternate_operator logical_operator? ? SEMANTIC_AND : LOGICAL_AND end # Returns the inverse keyword of the `and` node as a string. # Returns `||` for `&&` and `or` for `and`. # # @return [String] the inverse of the `and` operator def inverse_operator logical_operator? ? LOGICAL_OR : SEMANTIC_OR end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/procarg0_node.rb
lib/rubocop/ast/node/procarg0_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `procarg0` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all `arg` nodes within RuboCop. class Procarg0Node < ArgNode # Returns the name of an argument. # # @return [Symbol, nil] the name of the argument def name node_parts[0].name end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/case_node.rb
lib/rubocop/ast/node/case_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `case` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `case` nodes within RuboCop. class CaseNode < Node include ConditionalNode # Returns the keyword of the `case` statement as a string. # # @return [String] the keyword of the `case` statement def keyword 'case' end # @deprecated Use `when_branches.each` def each_when(&block) return when_branches.to_enum(__method__) unless block when_branches.each(&block) self end # Returns an array of all the when branches in the `case` statement. # # @return [Array<WhenNode>] an array of `when` nodes def when_branches node_parts[1...-1] end # Returns an array of all the when branches in the `case` statement. # # @return [Array<Node, nil>] an array of the bodies of the when branches # and the else (if any). Note that these bodies could be nil. def branches bodies = when_branches.map(&:body) bodies.push(else_branch) if else? bodies end # Returns the else branch of the `case` statement, if any. # # @return [Node] the else branch node of the `case` statement # @return [nil] if the case statement does not have an else branch. def else_branch node_parts[-1] end # Checks whether this case statement has an `else` branch. # # @return [Boolean] whether the `case` statement has an `else` branch def else? loc.else end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/arg_node.rb
lib/rubocop/ast/node/arg_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `arg`, `optarg`, `restarg`, `kwarg`, `kwoptarg`, # `kwrestarg`, `blockarg`, `shadowarg` and `forward_arg` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all `arg` nodes within RuboCop. class ArgNode < Node # Returns the name of an argument. # # @return [Symbol, nil] the name of the argument def name node_parts[0] end # Returns the default value of the argument, if any. # # @return [Node, nil] the default value of the argument def default_value return unless default? node_parts[1] end # Checks whether the argument has a default value # # @return [Boolean] whether the argument has a default value def default? optarg_type? || kwoptarg_type? end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/break_node.rb
lib/rubocop/ast/node/break_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `break` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `break` nodes within RuboCop. class BreakNode < Node include ParameterizedNode::WrappedArguments end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/str_node.rb
lib/rubocop/ast/node/str_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `str`, `dstr`, and `xstr` nodes. This will be used # in place of a plain node when the builder constructs the AST, making # its methods available to all `str` nodes within RuboCop. class StrNode < Node include BasicLiteralNode PERCENT_LITERAL_TYPES = { :% => /\A%(?=[^a-zA-Z])/, :q => /\A%q/, :Q => /\A%Q/ }.freeze private_constant :PERCENT_LITERAL_TYPES def single_quoted? loc_is?(:begin, "'") end def double_quoted? loc_is?(:begin, '"') end def character_literal? loc_is?(:begin, '?') end def heredoc? loc.is_a?(Parser::Source::Map::Heredoc) end # Checks whether the string literal is delimited by percent brackets. # # @overload percent_literal? # Check for any string percent literal. # # @overload percent_literal?(type) # Check for a string percent literal of type `type`. # # @param type [Symbol] an optional percent literal type # # @return [Boolean] whether the string is enclosed in percent brackets def percent_literal?(type = nil) return false unless loc?(:begin) if type loc.begin.source.match?(PERCENT_LITERAL_TYPES.fetch(type)) else loc.begin.source.start_with?('%') end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/const_node.rb
lib/rubocop/ast/node/const_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `const` nodes. class ConstNode < Node include ConstantNode end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/var_node.rb
lib/rubocop/ast/node/var_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `lvar`, `ivar`, `cvar` and `gvar` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all assignment nodes within RuboCop. class VarNode < Node # @return [Symbol] The name of the variable. def name node_parts[0] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/and_asgn_node.rb
lib/rubocop/ast/node/and_asgn_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `op_asgn` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all assignment nodes within RuboCop. class AndAsgnNode < OpAsgnNode # The operator being used for assignment as a symbol. # # @return [Symbol] the assignment operator def operator :'&&' end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/super_node.rb
lib/rubocop/ast/node/super_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `super`- and `zsuper` nodes. This will be used in # place of a plain node when the builder constructs the AST, making its # methods available to all `super`- and `zsuper` nodes within RuboCop. class SuperNode < Node include ParameterizedNode include MethodDispatchNode # Custom destructuring method. This can be used to normalize # destructuring for different variations of the node. # # @return [Array] the different parts of the `super` node def node_parts [nil, :super, *to_a] end alias arguments children end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/keyword_begin_node.rb
lib/rubocop/ast/node/keyword_begin_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `kwbegin` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `kwbegin` nodes within RuboCop. class KeywordBeginNode < Node # Returns the body of the `kwbegin` block. Returns `self` if the `kwbegin` contains # multiple nodes. # # @return [Node, nil] The body of the `kwbegin`. def body return unless node_parts.any? if rescue_node rescue_node.body elsif ensure_node ensure_node.node_parts[0] elsif node_parts.one? node_parts[0] else self end end # Returns the `rescue` node of the `kwbegin` block, if one is present. # # @return [Node, nil] The `rescue` node within `kwbegin`. def ensure_node node_parts[0] if node_parts[0]&.ensure_type? end # Returns the `rescue` node of the `kwbegin` block, if one is present. # # @return [Node, nil] The `rescue` node within `kwbegin`. def rescue_node return ensure_node&.rescue_node if ensure_node&.rescue_node node_parts[0] if node_parts[0]&.rescue_type? end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/casgn_node.rb
lib/rubocop/ast/node/casgn_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `casgn` nodes. # This will be used in place of a plain node when the builder constructs # the AST, making its methods available to all assignment nodes within RuboCop. class CasgnNode < Node include ConstantNode alias name short_name alias lhs short_name # The expression being assigned to the variable. # # @return [Node] the expression being assigned. def expression node_parts[2] end alias rhs expression end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/index_node.rb
lib/rubocop/ast/node/index_node.rb
# frozen_string_literal: true module RuboCop module AST # Used for modern support only! # Not as thoroughly tested as legacy equivalent # # $ ruby-parse -e "foo[:bar]" # (index # (send nil :foo) # (sym :bar)) # $ ruby-parse --legacy -e "foo[:bar]" # (send # (send nil :foo) :[] # (sym :bar)) # # The main RuboCop runs in legacy mode; this node is only used # if user `AST::Builder.modernize` or `AST::Builder.emit_index=true` class IndexNode < Node include ParameterizedNode::RestArguments include MethodDispatchNode # For similarity with legacy mode def attribute_accessor? false end # For similarity with legacy mode def assignment_method? false end # For similarity with legacy mode def method_name :[] end private # An array containing the arguments of the dispatched method. # # @return [Array<Node>] the arguments of the dispatched method def first_argument_index 1 end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/dstr_node.rb
lib/rubocop/ast/node/dstr_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `dstr` nodes. This will be used # in place of a plain node when the builder constructs the AST, making # its methods available to all `dstr` nodes within RuboCop. class DstrNode < StrNode def value child_nodes.map do |child| child.respond_to?(:value) ? child.value : child.source end.join end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/until_node.rb
lib/rubocop/ast/node/until_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `until` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `until` nodes within RuboCop. class UntilNode < Node include ConditionalNode include ModifierNode # Returns the keyword of the `until` statement as a string. # # @return [String] the keyword of the `until` statement def keyword 'until' end # Returns the inverse keyword of the `until` node as a string. # Returns `while` for `until` nodes and vice versa. # # @return [String] the inverse keyword of the `until` statement def inverse_keyword 'while' end # Checks whether the `until` node has a `do` keyword. # # @return [Boolean] whether the `until` node has a `do` keyword def do? loc_is?(:begin, 'do') end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/keyword_splat_node.rb
lib/rubocop/ast/node/keyword_splat_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `kwsplat` and `forwarded_kwrestarg` nodes. This will be used in # place of a plain node when the builder constructs the AST, making its methods available to # all `kwsplat` and `forwarded_kwrestarg` nodes within RuboCop. class KeywordSplatNode < Node include HashElementNode DOUBLE_SPLAT = '**' private_constant :DOUBLE_SPLAT # This is used for duck typing with `pair` nodes which also appear as # `hash` elements. # # @return [false] def hash_rocket? false end # This is used for duck typing with `pair` nodes which also appear as # `hash` elements. # # @return [false] def colon? false end # Returns the operator for the `kwsplat` as a string. # # @return [String] the double splat operator def operator DOUBLE_SPLAT end # Custom destructuring method. This is used to normalize the branches # for `pair` and `kwsplat` nodes, to add duck typing to `hash` elements. # # @return [Array<KeywordSplatNode>] the different parts of the `kwsplat` def node_parts [self, self] end # This provides `forwarded_kwrestarg` node to return true to be compatible with `kwsplat` node. # # @return [true] def kwsplat_type? true end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/csend_node.rb
lib/rubocop/ast/node/csend_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `csend` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `csend` nodes within RuboCop. class CsendNode < SendNode def send_type? false end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/args_node.rb
lib/rubocop/ast/node/args_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `args` nodes. This will be used in place of a plain # node when the builder constructs the AST, making its methods available # to all `args` nodes within RuboCop. class ArgsNode < Node include CollectionNode # It returns true if arguments are empty and delimiters do not exist. # @example: # # true # def x; end # x { } # -> {} # # # false # def x(); end # def x a; end # x { || } # -> () {} # -> a {} def empty_and_without_delimiters? loc.expression.nil? end # Yield each argument from the collection. # Arguments can be inside `mlhs` nodes in the case of destructuring, so this # flattens the collection to just `arg`, `optarg`, `restarg`, `kwarg`, # `kwoptarg`, `kwrestarg`, `blockarg`, `forward_arg` and `shadowarg`. # # @return [Array<Node>] array of argument nodes. def argument_list each_descendant(:argument).to_a.freeze end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/self_class_node.rb
lib/rubocop/ast/node/self_class_node.rb
# frozen_string_literal: true module RuboCop module AST # A node extension for `sclass` nodes. This will be used in place of a # plain node when the builder constructs the AST, making its methods # available to all `sclass` nodes within RuboCop. class SelfClassNode < Node # The identifier for this `sclass` node. (Always `self`.) # # @return [Node] the identifier of the class def identifier node_parts[0] end # The body of this `sclass` node. # # @return [Node, nil] the body of the class def body node_parts[1] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/basic_literal_node.rb
lib/rubocop/ast/node/mixin/basic_literal_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for primitive literal nodes: `sym`, `str`, # `int`, `float`, `rational`, `complex`... module BasicLiteralNode # Returns the value of the literal. # # @return [mixed] the value of the literal def value node_parts[0] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/constant_node.rb
lib/rubocop/ast/node/mixin/constant_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for nodes that deal with constants: # `const`, `casgn`. module ConstantNode # @return [Node, nil] the node associated with the scope (e.g. cbase, const, ...) def namespace children[0] end # @return [Symbol] the demodulized name of the constant: "::Foo::Bar" => :Bar def short_name children[1] end # @return [Boolean] if the constant is a Module / Class, according to the standard convention. # Note: some classes might have uppercase in which case this method # returns false def module_name? short_name.match?(/[[:lower:]]/) end alias class_name? module_name? # @return [Boolean] if the constant starts with `::` (aka s(:cbase)) def absolute? return false unless namespace each_path.first.cbase_type? end # @return [Boolean] if the constant does not start with `::` (aka s(:cbase)) def relative? !absolute? end # Yield nodes for the namespace # # For `::Foo::Bar::BAZ` => yields: # s(:cbase), then # s(:const, :Foo), then # s(:const, s(:const, :Foo), :Bar) def each_path(&block) return to_enum(__method__) unless block descendants = [] last = self loop do last = last.children.first break if last.nil? descendants << last break unless last.const_type? end descendants.reverse_each(&block) self end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/conditional_node.rb
lib/rubocop/ast/node/mixin/conditional_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for nodes that have conditions: # `if`, `while`, `until`, `case`. # This currently doesn't include `when` nodes, because they have multiple # conditions, and need to be checked for that. module ConditionalNode # Checks whether the condition of the node is written on a single line. # # @return [Boolean] whether the condition is on a single line def single_line_condition? loc.keyword.line == condition.source_range.line end # Checks whether the condition of the node is written on more than # one line. # # @return [Boolean] whether the condition is on more than one line def multiline_condition? !single_line_condition? end # Returns the condition of the node. This works together with each node's # custom destructuring method to select the correct part of the node. # # @return [Node, nil] the condition of the node def condition node_parts[0] end # Returns the body associated with the condition. This works together with # each node's custom destructuring method to select the correct part of # the node. # # @note For `if` nodes, this is the truthy branch. # # @return [Node, nil] the body of the node def body node_parts[1] end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/binary_operator_node.rb
lib/rubocop/ast/node/mixin/binary_operator_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for nodes that are binary operations: # `or`, `and` ... module BinaryOperatorNode # Returns the left hand side node of the binary operation. # # @return [Node] the left hand side of the binary operation def lhs node_parts[0] end # Returns the right hand side node of the binary operation. # # @return [Node] the right hand side of the binary operation def rhs node_parts[1] end # Returns all of the conditions, including nested conditions, # of the binary operation. # # @return [Array<Node>] the left and right hand side of the binary # operation and the let and right hand side of any nested binary # operators def conditions lhs, rhs = *self lhs = lhs.children.first if lhs.begin_type? rhs = rhs.children.first if rhs.begin_type? [lhs, rhs].each_with_object([]) do |side, collection| if side.operator_keyword? collection.concat(side.conditions) else collection << side end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/collection_node.rb
lib/rubocop/ast/node/mixin/collection_node.rb
# frozen_string_literal: true module RuboCop module AST # A mixin that helps give collection nodes array polymorphism. module CollectionNode extend SimpleForwardable ARRAY_METHODS = (Array.instance_methods - Object.instance_methods - [:to_a]).freeze private_constant :ARRAY_METHODS def_delegators :to_a, *ARRAY_METHODS end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/method_dispatch_node.rb
lib/rubocop/ast/node/mixin/method_dispatch_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for nodes that are a kind of method dispatch: # `send`, `csend`, `super`, `zsuper`, `yield`, `defined?`, # and (modern only): `index`, `indexasgn`, `lambda` module MethodDispatchNode # rubocop:disable Metrics/ModuleLength extend NodePattern::Macros include MethodIdentifierPredicates ARITHMETIC_OPERATORS = %i[+ - * / % **].freeze private_constant :ARITHMETIC_OPERATORS SPECIAL_MODIFIERS = %w[private protected].freeze private_constant :SPECIAL_MODIFIERS # The receiving node of the method dispatch. # # @return [Node, nil] the receiver of the dispatched method or `nil` def receiver node_parts[0] end # The name of the dispatched method as a symbol. # # @return [Symbol] the name of the dispatched method def method_name node_parts[1] end # The source range for the method name or keyword that dispatches this call. # # @return [Parser::Source::Range] the source range for the method name or keyword def selector if loc?(:keyword) loc.keyword else loc.selector end end # The `block`, `numblock`, or `itblock` node associated with this method dispatch, if any. # # @return [BlockNode, nil] the `block`, `numblock`, or `itblock` node associated with this # method call or `nil` def block_node parent if block_literal? end # Checks whether the dispatched method is a macro method. A macro method # is defined as a method that sits in a class, module, or block body and # has an implicit receiver. # # @note This does not include DSLs that use nested blocks, like RSpec # # @return [Boolean] whether the dispatched method is a macro method def macro? !receiver && in_macro_scope? end # Checks whether the dispatched method is an access modifier. # # @return [Boolean] whether the dispatched method is an access modifier def access_modifier? bare_access_modifier? || non_bare_access_modifier? end # Checks whether the dispatched method is a bare access modifier that # affects all methods defined after the macro. # # @return [Boolean] whether the dispatched method is a bare # access modifier def bare_access_modifier? macro? && bare_access_modifier_declaration? end # Checks whether the dispatched method is a non-bare access modifier that # affects only the method it receives. # # @return [Boolean] whether the dispatched method is a non-bare # access modifier def non_bare_access_modifier? macro? && non_bare_access_modifier_declaration? end # Checks whether the dispatched method is a bare `private` or `protected` # access modifier that affects all methods defined after the macro. # # @return [Boolean] whether the dispatched method is a bare # `private` or `protected` access modifier def special_modifier? bare_access_modifier? && SPECIAL_MODIFIERS.include?(source) end # Checks whether the name of the dispatched method matches the argument # and has an implicit receiver. # # @param [Symbol, String] name the method name to check for # @return [Boolean] whether the method name matches the argument def command?(name) !receiver && method?(name) end # Checks whether the dispatched method is a setter method. # # @return [Boolean] whether the dispatched method is a setter def setter_method? loc?(:operator) end alias assignment? setter_method? # Checks whether the dispatched method uses a dot to connect the # receiver and the method name. # # This is useful for comparison operators, which can be called either # with or without a dot, i.e. `foo == bar` or `foo.== bar`. # # @return [Boolean] whether the method was called with a connecting dot def dot? loc_is?(:dot, '.') end # Checks whether the dispatched method uses a double colon to connect the # receiver and the method name. # # @return [Boolean] whether the method was called with a connecting dot def double_colon? loc_is?(:dot, '::') end # Checks whether the dispatched method uses a safe navigation operator to # connect the receiver and the method name. # # @return [Boolean] whether the method was called with a connecting dot def safe_navigation? loc_is?(:dot, '&.') end # Checks whether the *explicit* receiver of this method dispatch is # `self`. # # @return [Boolean] whether the receiver of this method dispatch is `self` def self_receiver? receiver&.self_type? end # Checks whether the *explicit* receiver of this method dispatch is a # `const` node. # # @return [Boolean] whether the receiver of this method dispatch # is a `const` node def const_receiver? receiver&.const_type? end # Checks whether the method dispatch is the implicit form of `#call`, # e.g. `foo.(bar)`. # # @return [Boolean] whether the method is the implicit form of `#call` def implicit_call? method?(:call) && !selector end # Whether this method dispatch has an explicit block. # # @return [Boolean] whether the dispatched method has a block def block_literal? parent&.any_block_type? && eql?(parent.send_node) end # Checks whether this node is an arithmetic operation # # @return [Boolean] whether the dispatched method is an arithmetic # operation def arithmetic_operation? ARITHMETIC_OPERATORS.include?(method_name) end # Checks if this node is part of a chain of `def` or `defs` modifiers. # # @example # # private def foo; end # # @return whether the `def|defs` node is a modifier or not. # See also `def_modifier` that returns the node or `nil` def def_modifier?(node = self) !!def_modifier(node) end # Checks if this node is part of a chain of `def` or `defs` modifiers. # # @example # # private def foo; end # # @return [Node | nil] returns the `def|defs` node this is a modifier for, # or `nil` if it isn't a def modifier def def_modifier(node = self) arg = node.children[2] return unless node.send_type? && node.receiver.nil? && arg.is_a?(::AST::Node) return arg if arg.any_def_type? def_modifier(arg) end # Checks whether this is a lambda. Some versions of parser parses # non-literal lambdas as a method send. # # @return [Boolean] whether this method is a lambda def lambda? block_literal? && command?(:lambda) end # Checks whether this is a lambda literal (stabby lambda.) # # @example # # -> (foo) { bar } # # @return [Boolean] whether this method is a lambda literal def lambda_literal? loc.expression.source == '->' && block_literal? end # Checks whether this is a unary operation. # # @example # # -foo # # @return [Boolean] whether this method is a unary operation def unary_operation? return false unless selector operator_method? && loc.expression.begin_pos == selector.begin_pos end # Checks whether this is a binary operation. # # @example # # foo + bar # # @return [Boolean] whether this method is a binary operation def binary_operation? return false unless selector operator_method? && loc.expression.begin_pos != selector.begin_pos end private # @!method in_macro_scope?(node = self) def_node_matcher :in_macro_scope?, <<~PATTERN { root? # Either a root node, ^{ # or the parent is... sclass class module class_constructor? # a class-like node [ { # or some "wrapper" kwbegin begin any_block (if _condition <%0 _>) # note: we're excluding the condition of `if` nodes } #in_macro_scope? # that is itself in a macro scope ] } } PATTERN # @!method adjacent_def_modifier?(node = self) def_node_matcher :adjacent_def_modifier?, <<~PATTERN (send nil? _ (any_def ...)) PATTERN # @!method bare_access_modifier_declaration?(node = self) def_node_matcher :bare_access_modifier_declaration?, <<~PATTERN (send nil? {:public :protected :private :module_function}) PATTERN # @!method non_bare_access_modifier_declaration?(node = self) def_node_matcher :non_bare_access_modifier_declaration?, <<~PATTERN (send nil? {:public :protected :private :module_function} _+) PATTERN end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/method_identifier_predicates.rb
lib/rubocop/ast/node/mixin/method_identifier_predicates.rb
# frozen_string_literal: true module RuboCop module AST # Common predicates for nodes that reference method identifiers: # `send`, `csend`, `def`, `defs`, `super`, `zsuper` # # @note this mixin expects `#method_name` and `#receiver` to be implemented module MethodIdentifierPredicates # rubocop:disable Metrics/ModuleLength ENUMERATOR_METHODS = %i[collect collect_concat detect downto each find find_all find_index inject loop map! map reduce reject reject! reverse_each select select! times upto].to_set.freeze private_constant :ENUMERATOR_METHODS ENUMERABLE_METHODS = (Enumerable.instance_methods + [:each]).to_set.freeze private_constant :ENUMERABLE_METHODS # http://phrogz.net/programmingruby/language.html#table_18.4 OPERATOR_METHODS = %i[| ^ & <=> == === =~ > >= < <= << >> + - * / % ** ~ +@ -@ !@ ~@ [] []= ! != !~ `].to_set.freeze private_constant :OPERATOR_METHODS NONMUTATING_BINARY_OPERATOR_METHODS = %i[* / % + - == === != < > <= >= <=>].to_set.freeze private_constant :NONMUTATING_BINARY_OPERATOR_METHODS NONMUTATING_UNARY_OPERATOR_METHODS = %i[+@ -@ ~ !].to_set.freeze private_constant :NONMUTATING_UNARY_OPERATOR_METHODS NONMUTATING_OPERATOR_METHODS = (NONMUTATING_BINARY_OPERATOR_METHODS + NONMUTATING_UNARY_OPERATOR_METHODS).freeze private_constant :NONMUTATING_OPERATOR_METHODS NONMUTATING_ARRAY_METHODS = %i[ all? any? assoc at bsearch bsearch_index collect combination compact count cycle deconstruct difference dig drop drop_while each each_index empty? eql? fetch filter find_index first flatten hash include? index inspect intersection join last length map max min minmax none? one? pack permutation product rassoc reject repeated_combination repeated_permutation reverse reverse_each rindex rotate sample select shuffle size slice sort sum take take_while to_a to_ary to_h to_s transpose union uniq values_at zip | ].to_set.freeze private_constant :NONMUTATING_ARRAY_METHODS NONMUTATING_HASH_METHODS = %i[ any? assoc compact dig each each_key each_pair each_value empty? eql? fetch fetch_values filter flatten has_key? has_value? hash include? inspect invert key key? keys? length member? merge rassoc rehash reject select size slice to_a to_h to_hash to_proc to_s transform_keys transform_values value? values values_at ].to_set.freeze private_constant :NONMUTATING_HASH_METHODS NONMUTATING_STRING_METHODS = %i[ ascii_only? b bytes bytesize byteslice capitalize casecmp casecmp? center chars chomp chop chr codepoints count crypt delete delete_prefix delete_suffix downcase dump each_byte each_char each_codepoint each_grapheme_cluster each_line empty? encode encoding end_with? eql? getbyte grapheme_clusters gsub hash hex include index inspect intern length lines ljust lstrip match match? next oct ord partition reverse rindex rjust rpartition rstrip scan scrub size slice squeeze start_with? strip sub succ sum swapcase to_a to_c to_f to_i to_r to_s to_str to_sym tr tr_s unicode_normalize unicode_normalized? unpack unpack1 upcase upto valid_encoding? ].to_set.freeze private_constant :NONMUTATING_STRING_METHODS # Checks whether the method name matches the argument. # # @param [Symbol, String] name the method name to check for # @return [Boolean] whether the method name matches the argument def method?(name) method_name == name.to_sym end # Checks whether the method is an operator method. # # @return [Boolean] whether the method is an operator def operator_method? OPERATOR_METHODS.include?(method_name) end # Checks whether the method is a nonmutating binary operator method. # # @return [Boolean] whether the method is a nonmutating binary operator method def nonmutating_binary_operator_method? NONMUTATING_BINARY_OPERATOR_METHODS.include?(method_name) end # Checks whether the method is a nonmutating unary operator method. # # @return [Boolean] whether the method is a nonmutating unary operator method def nonmutating_unary_operator_method? NONMUTATING_UNARY_OPERATOR_METHODS.include?(method_name) end # Checks whether the method is a nonmutating operator method. # # @return [Boolean] whether the method is a nonmutating operator method def nonmutating_operator_method? NONMUTATING_OPERATOR_METHODS.include?(method_name) end # Checks whether the method is a nonmutating Array method. # # @return [Boolean] whether the method is a nonmutating Array method def nonmutating_array_method? NONMUTATING_ARRAY_METHODS.include?(method_name) end # Checks whether the method is a nonmutating Hash method. # # @return [Boolean] whether the method is a nonmutating Hash method def nonmutating_hash_method? NONMUTATING_HASH_METHODS.include?(method_name) end # Checks whether the method is a nonmutating String method. # # @return [Boolean] whether the method is a nonmutating String method def nonmutating_string_method? NONMUTATING_STRING_METHODS.include?(method_name) end # Checks whether the method is a comparison method. # # @return [Boolean] whether the method is a comparison def comparison_method? Node::COMPARISON_OPERATORS.include?(method_name) end # Checks whether the method is an assignment method. # # @return [Boolean] whether the method is an assignment def assignment_method? !comparison_method? && method_name.to_s.end_with?('=') end # Checks whether the method is an enumerator method. # # @return [Boolean] whether the method is an enumerator def enumerator_method? ENUMERATOR_METHODS.include?(method_name) || method_name.to_s.start_with?('each_') end # Checks whether the method is an Enumerable method. # # @return [Boolean] whether the method is an Enumerable method def enumerable_method? ENUMERABLE_METHODS.include?(method_name) end # Checks whether the method is a predicate method. # # @return [Boolean] whether the method is a predicate method def predicate_method? method_name.to_s.end_with?('?') end # Checks whether the method is a bang method. # # @return [Boolean] whether the method is a bang method def bang_method? method_name.to_s.end_with?('!') end # Checks whether the method is a camel case method, # e.g. `Integer()`. # # @return [Boolean] whether the method is a camel case method def camel_case_method? method_name.to_s =~ /\A[A-Z]/ end # Checks whether the *explicit* receiver of this node is `self`. # # @return [Boolean] whether the receiver of this node is `self` def self_receiver? receiver&.self_type? end # Checks whether the *explicit* receiver of node is a `const` node. # # @return [Boolean] whether the receiver of this node is a `const` node def const_receiver? receiver&.const_type? end # Checks whether this is a negation method, i.e. `!` or keyword `not`. # # @return [Boolean] whether this method is a negation method def negation_method? receiver && method_name == :! end # Checks whether this is a prefix not method, e.g. `not foo`. # # @return [Boolean] whether this method is a prefix not def prefix_not? negation_method? && loc.selector.is?('not') end # Checks whether this is a prefix bang method, e.g. `!foo`. # # @return [Boolean] whether this method is a prefix bang def prefix_bang? negation_method? && loc.selector.is?('!') end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/modifier_node.rb
lib/rubocop/ast/node/mixin/modifier_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for nodes that can be used as modifiers: # `if`, `while`, `until` module ModifierNode # Checks whether the node is in a modifier form, i.e. a condition # trailing behind an expression. # # @return [Boolean] whether the node is a modifier def modifier_form? loc.end.nil? end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/descendence.rb
lib/rubocop/ast/node/mixin/descendence.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for primitive literal nodes: `sym`, `str`, # `int`, `float`, ... module Descendence # Calls the given block for each child node. # If no block is given, an `Enumerator` is returned. # # Note that this is different from `node.children.each { |child| ... }` # which yields all children including non-node elements. # # @overload each_child_node # Yield all nodes. # @overload each_child_node(type, ...) # Yield only nodes matching any of the types. # @param [Symbol] type a node type # @yieldparam [Node] node each child node # @return [self] if a block is given # @return [Enumerator] if no block is given def each_child_node(*types) return to_enum(__method__, *types) unless block_given? children.each do |child| next unless child.is_a?(::AST::Node) yield child if types.empty? || child.type?(*types) end self end # Returns an array of child nodes. # This is a shorthand for `node.each_child_node.to_a`. # # @return [Array<Node>] an array of child nodes def child_nodes # Iterate child nodes directly to avoid allocating an Enumerator. nodes = [] each_child_node { |node| nodes << node } nodes end # Calls the given block for each descendant node with depth first order. # If no block is given, an `Enumerator` is returned. # # @overload each_descendant # Yield all nodes. # @overload each_descendant(type) # Yield only nodes matching the type. # @param [Symbol] type a node type # @overload each_descendant(type_a, type_b, ...) # Yield only nodes matching any of the types. # @param [Symbol] type_a a node type # @param [Symbol] type_b a node type # @yieldparam [Node] node each descendant node # @return [self] if a block is given # @return [Enumerator] if no block is given def each_descendant(*types, &block) return to_enum(__method__, *types) unless block visit_descendants(types, &block) self end # Returns an array of descendant nodes. # This is a shorthand for `node.each_descendant.to_a`. # # @return [Array<Node>] an array of descendant nodes def descendants each_descendant.to_a end # Calls the given block for the receiver and each descendant node in # depth-first order. # If no block is given, an `Enumerator` is returned. # # This method would be useful when you treat the receiver node as the root # of a tree and want to iterate over all nodes in the tree. # # @overload each_node # Yield all nodes. # @overload each_node(type) # Yield only nodes matching the type. # @param [Symbol] type a node type # @overload each_node(type_a, type_b, ...) # Yield only nodes matching any of the types. # @param [Symbol] type_a a node type # @param [Symbol] type_b a node type # @yieldparam [Node] node each node # @return [self] if a block is given # @return [Enumerator] if no block is given def each_node(*types, &block) return to_enum(__method__, *types) unless block yield self if types.empty? || type?(*types) visit_descendants(types, &block) self end protected def visit_descendants(types, &block) children.each do |child| next unless child.is_a?(::AST::Node) yield child if types.empty? || child.type?(*types) child.visit_descendants(types, &block) end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/parameterized_node.rb
lib/rubocop/ast/node/mixin/parameterized_node.rb
# frozen_string_literal: true module RuboCop module AST # Requires implementing `arguments`. # # Common functionality for nodes that are parameterized: # `send`, `super`, `zsuper`, `def`, `defs` # and (modern only): `index`, `indexasgn`, `lambda` module ParameterizedNode # Checks whether this node's arguments are wrapped in parentheses. # # @return [Boolean] whether this node's arguments are # wrapped in parentheses def parenthesized? loc_is?(:end, ')') end # A shorthand for getting the first argument of the node. # Equivalent to `arguments.first`. # # @return [Node, nil] the first argument of the node, # or `nil` if there are no arguments def first_argument arguments[0] end # A shorthand for getting the last argument of the node. # Equivalent to `arguments.last`. # # @return [Node, nil] the last argument of the node, # or `nil` if there are no arguments def last_argument arguments[-1] end # Checks whether this node has any arguments. # # @return [Boolean] whether this node has any arguments def arguments? !arguments.empty? end # Checks whether any argument of the node is a splat # argument, i.e. `*splat`. # # @return [Boolean] whether the node is a splat argument def splat_argument? arguments? && (arguments.any?(&:splat_type?) || arguments.any?(&:restarg_type?)) end alias rest_argument? splat_argument? # Whether the last argument of the node is a block pass, # i.e. `&block`. # # @return [Boolean] whether the last argument of the node is a block pass def block_argument? arguments? && last_argument.type?(:block_pass, :blockarg) end # A specialized `ParameterizedNode` for node that have a single child # containing either `nil`, an argument, or a `begin` node with all the # arguments module WrappedArguments include ParameterizedNode # @return [Array] The arguments of the node. def arguments first = children.first if first&.begin_type? first.children else children end end end # A specialized `ParameterizedNode`. # Requires implementing `first_argument_index` # Implements `arguments` as `children[first_argument_index..-1]` # and optimizes other calls module RestArguments include ParameterizedNode EMPTY_ARGUMENTS = [].freeze # @return [Array<Node>] arguments, if any def arguments if arguments? children.drop(first_argument_index).freeze else # Skip unneeded Array allocation. EMPTY_ARGUMENTS end end # A shorthand for getting the first argument of the node. # Equivalent to `arguments.first`. # # @return [Node, nil] the first argument of the node, # or `nil` if there are no arguments def first_argument children[first_argument_index] end # A shorthand for getting the last argument of the node. # Equivalent to `arguments.last`. # # @return [Node, nil] the last argument of the node, # or `nil` if there are no arguments def last_argument children[-1] if arguments? end # Checks whether this node has any arguments. # # @return [Boolean] whether this node has any arguments def arguments? children.size > first_argument_index end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/hash_element_node.rb
lib/rubocop/ast/node/mixin/hash_element_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for nodes that can be used as hash elements: # `pair`, `kwsplat` module HashElementNode # Returns the key of this `hash` element. # # @note For keyword splats, this returns the whole node # # @return [Node] the key of the hash element def key node_parts[0] end # Returns the value of this `hash` element. # # @note For keyword splats, this returns the whole node # # @return [Node] the value of the hash element def value node_parts[1] end # Checks whether this `hash` element is on the same line as `other`. # # @note A multiline element is considered to be on the same line if it # shares any of its lines with `other` # # @return [Boolean] whether this element is on the same line as `other` def same_line?(other) loc.last_line == other.loc.line || loc.line == other.loc.last_line end # Returns the delta between this pair's key and the argument pair's. # # @note Keys on the same line always return a delta of 0 # @note Keyword splats always return a delta of 0 for right alignment # # @param [Symbol] alignment whether to check the left or right side # @return [Integer] the delta between the two keys def key_delta(other, alignment = :left) HashElementDelta.new(self, other).key_delta(alignment) end # Returns the delta between this element's value and the argument's. # # @note Keyword splats always return a delta of 0 # # @return [Integer] the delta between the two values def value_delta(other) HashElementDelta.new(self, other).value_delta end # Returns the delta between this element's delimiter and the argument's. # # @note Pairs with different delimiter styles return a delta of 0 # # @return [Integer] the delta between the two delimiters def delimiter_delta(other) HashElementDelta.new(self, other).delimiter_delta end # A helper class for comparing the positions of different parts of a # `pair` node. class HashElementDelta def initialize(first, second) @first = first @second = second raise ArgumentError unless valid_argument_types? end def key_delta(alignment = :left) return 0 if first.same_line?(second) return 0 if keyword_splat? && alignment == :right delta(first.key.loc, second.key.loc, alignment) end def value_delta return 0 if first.same_line?(second) return 0 if keyword_splat? delta(first.value.loc, second.value.loc) end def delimiter_delta return 0 if first.same_line?(second) return 0 if first.delimiter != second.delimiter delta(first.loc.operator, second.loc.operator) end private attr_reader :first, :second def valid_argument_types? [first, second].all? do |argument| # rubocop:disable InternalAffairs/NodeTypeMultiplePredicates argument.pair_type? || argument.kwsplat_type? # rubocop:enable InternalAffairs/NodeTypeMultiplePredicates end end def delta(first, second, alignment = :left) case alignment when :left first.column - second.column when :right first.last_column - second.last_column else 0 end end def keyword_splat? [first, second].any?(&:kwsplat_type?) end end private_constant :HashElementDelta end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/numeric_node.rb
lib/rubocop/ast/node/mixin/numeric_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for primitive numeric nodes: `int`, `float`, `rational`, `complex`... module NumericNode SIGN_REGEX = /\A[+-]/.freeze private_constant :SIGN_REGEX # Checks whether this is literal has a sign. # # @example # # +42 # # @return [Boolean] whether this literal has a sign. def sign? source.match?(SIGN_REGEX) end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node/mixin/predicate_operator_node.rb
lib/rubocop/ast/node/mixin/predicate_operator_node.rb
# frozen_string_literal: true module RuboCop module AST # Common functionality for nodes that are predicates: # `or`, `and` ... module PredicateOperatorNode LOGICAL_AND = '&&' private_constant :LOGICAL_AND SEMANTIC_AND = 'and' private_constant :SEMANTIC_AND LOGICAL_OR = '||' private_constant :LOGICAL_OR SEMANTIC_OR = 'or' private_constant :SEMANTIC_OR LOGICAL_OPERATORS = [LOGICAL_AND, LOGICAL_OR].freeze private_constant :LOGICAL_OPERATORS SEMANTIC_OPERATORS = [SEMANTIC_AND, SEMANTIC_OR].freeze private_constant :SEMANTIC_OPERATORS # Returns the operator as a string. # # @return [String] the operator def operator loc.operator.source end # Checks whether this is a logical operator. # # @return [Boolean] whether this is a logical operator def logical_operator? LOGICAL_OPERATORS.include?(operator) end # Checks whether this is a semantic operator. # # @return [Boolean] whether this is a semantic operator def semantic_operator? SEMANTIC_OPERATORS.include?(operator) end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/with_meta.rb
lib/rubocop/ast/node_pattern/with_meta.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern class Parser # Overrides Parser to use `WithMeta` variants and provide additional methods class WithMeta < Parser # Overrides Lexer to token locations and comments class Lexer < NodePattern::Lexer attr_reader :source_buffer def initialize(str_or_buffer) @source_buffer = if str_or_buffer.respond_to?(:source) str_or_buffer else ::Parser::Source::Buffer.new('(string)', source: str_or_buffer) end @comments = [] super(@source_buffer.source) end def token(type, value) super(type, [value, pos]) end def emit_comment @comments << Comment.new(pos) super end # @return [::Parser::Source::Range] last match's position def pos ::Parser::Source::Range.new(source_buffer, ss.pos - ss.matched_size, ss.pos) end end # Overrides Builder to emit nodes with locations class Builder < NodePattern::Builder def emit_atom(type, token) value, loc = token begin_l = loc.resize(1) end_l = loc.end.adjust(begin_pos: -1) begin_l = nil if begin_l.source.match?(/\w/) end_l = nil if end_l.source.match?(/\w/) n(type, [value], source_map(token, begin_t: begin_l, end_t: end_l)) end def emit_unary_op(type, operator_t = nil, *children) children[-1] = children[-1].first if children[-1].is_a?(Array) # token? map = source_map(children.first.source_range, operator_t: operator_t) n(type, children, map) end def emit_list(type, begin_t, children, end_t) expr = children.first.source_range.join(children.last.source_range) map = source_map(expr, begin_t: begin_t, end_t: end_t) n(type, children, map) end def emit_call(type, selector_t, args = nil) selector, = selector_t begin_t, arg_nodes, end_t = args map = source_map(selector_t, begin_t: begin_t, end_t: end_t, selector_t: selector_t) n(type, [selector, *arg_nodes], map) end private def n(type, children, source_map) super(type, children, { location: source_map }) end def loc(token_or_range) return token_or_range[1] if token_or_range.is_a?(Array) token_or_range end def join_exprs(left_expr, right_expr) left_expr.source_range.join(right_expr.source_range) end def source_map(token_or_range, begin_t: nil, end_t: nil, operator_t: nil, selector_t: nil) expression_l = loc(token_or_range) expression_l = expression_l.expression if expression_l.respond_to?(:expression) locs = [begin_t, end_t, operator_t, selector_t].map { |token| loc(token) } begin_l, end_l, operator_l, selector_l = locs expression_l = locs.compact.inject(expression_l, :join) ::Parser::Source::Map::Send.new(_dot_l = nil, selector_l, begin_l, end_l, expression_l) .with_operator(operator_l) end end attr_reader :comments, :tokens def do_parse r = super @comments = @lexer.comments @tokens = @lexer.tokens r end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/compiler.rb
lib/rubocop/ast/node_pattern/compiler.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern # The top-level compiler holding the global state # Defers work to its subcompilers # # Doc on how this fits in the compiling process: # /docs/modules/ROOT/pages/node_pattern.adoc class Compiler extend SimpleForwardable attr_reader :captures, :named_parameters, :positional_parameters, :binding def initialize @temp_depth = 0 # avoid name clashes between temp variables @captures = 0 # number of captures seen @positional_parameters = 0 # highest % (param) number seen @named_parameters = Set[] # keyword parameters @binding = Binding.new # bound variables @atom_subcompiler = self.class::AtomSubcompiler.new(self) end def_delegators :binding, :bind def positional_parameter(number) @positional_parameters = number if number > @positional_parameters "param#{number}" end def named_parameter(name) @named_parameters << name name end # Enumerates `enum` while keeping track of state across # union branches (captures and unification). def each_union(enum, &block) enforce_same_captures(binding.union_bind(enum), &block) end def compile_as_atom(node) @atom_subcompiler.compile(node) end def compile_as_node_pattern(node, **options) self.class::NodePatternSubcompiler.new(self, **options).compile(node) end def compile_sequence(sequence, var:) self.class::SequenceSubcompiler.new(self, sequence: sequence, var: var).compile_sequence end def parser @parser ||= Parser.new end # Utilities def with_temp_variables(*names, &block) @temp_depth += 1 suffix = @temp_depth if @temp_depth > 1 names = block.parameters.map(&:last) if names.empty? names.map! { |name| "#{name}#{suffix}" } yield(*names) ensure @temp_depth -= 1 end def next_capture "captures[#{new_capture}]" end def freeze @named_parameters.freeze super end private def enforce_same_captures(enum) return to_enum __method__, enum unless block_given? captures_before = captures_after = nil enum.each do |node| captures_before ||= @captures @captures = captures_before yield node captures_after ||= @captures if captures_after != @captures raise Invalid, 'each branch must have same number of captures' end end end def new_capture @captures ensure @captures += 1 end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/sets.rb
lib/rubocop/ast/node_pattern/sets.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern # Utility to assign a set of values to a constant module Sets REGISTRY = Hash.new do |h, set| name = Sets.name(set).freeze Sets.const_set(name, set) h[set] = "::RuboCop::AST::NodePattern::Sets::#{name}" end MAX = 4 def self.name(set) elements = set elements = set.first(MAX - 1) << :etc if set.size > MAX name = elements.to_a.join('_').upcase.gsub(/[^A-Z0-9_]/, '') uniq("SET_#{name}") end def self.uniq(name) return name unless Sets.const_defined?(name) (2..Float::INFINITY).each do |i| uniq = "#{name}_#{i}" return uniq unless Sets.const_defined?(uniq) end end def self.[](set) REGISTRY[set] end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/node.rb
lib/rubocop/ast/node_pattern/node.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern # Base class for AST Nodes of a `NodePattern` class Node < ::Parser::AST::Node extend SimpleForwardable include ::RuboCop::AST::Descendence MATCHES_WITHIN_SET = %i[symbol number string].to_set.freeze private_constant :MATCHES_WITHIN_SET ### # To be overridden by subclasses ### def rest? false end def capture? false end # @return [Integer, Range] An Integer for fixed length terms, otherwise a Range. # Note: `arity.end` may be `Float::INFINITY` def arity 1 end # @return [Array<Node>, nil] replace node with result, or `nil` if no change requested. def in_sequence_head nil end ### # Utilities ### # @return [Array<Node>] def children_nodes children.grep(Node) end # @return [Node] most nodes have only one child def child children[0] end # @return [Integer] nb of captures that this node will emit def nb_captures children_nodes.sum(&:nb_captures) end # @return [Boolean] returns whether it matches a variable number of elements def variadic? arity.is_a?(Range) end # @return [Boolean] returns true for nodes having a Ruby literal equivalent # that matches within a Set (e.g. `42`, `:sym` but not `/regexp/`) def matches_within_set? MATCHES_WITHIN_SET.include?(type) end # @return [Range] arity as a Range def arity_range a = arity a.is_a?(Range) ? a : INT_TO_RANGE[a] end def with(type: @type, children: @children, location: @location) self.class.new(type, children, { location: location }) end def source_range loc.expression end INT_TO_RANGE = Hash.new { |h, k| h[k] = k..k } private_constant :INT_TO_RANGE # :nodoc: module ForbidInSeqHead def in_sequence_head raise NodePattern::Invalid, "A sequence can not start with a #{type}" end end ### # Subclasses for specific node types ### # Node class for `$something` class Capture < Node # Delegate most introspection methods to it's only child def_delegators :child, :arity, :rest? def capture? true end def nb_captures 1 + super end def in_sequence_head wildcard, original_child = child.in_sequence_head return unless original_child [wildcard, self] # ($...) => (_ $...) end end # Node class for `(type first second ...)` class Sequence < Node include ForbidInSeqHead def initialize(type, children = [], properties = {}) if (replace = children.first.in_sequence_head) children = [*replace, *children[1..]] end super end end # Node class for `predicate?(:arg, :list)` class Predicate < Node def method_name children.first end def arg_list children[1..] end end FunctionCall = Predicate # Node class for `int+` class Repetition < Node include ForbidInSeqHead def operator children[1] end ARITIES = { '*': 0..Float::INFINITY, '+': 1..Float::INFINITY, '?': 0..1 }.freeze def arity ARITIES[operator] end end # Node class for `...` class Rest < Node ARITY = (0..Float::INFINITY).freeze private_constant :ARITY def rest? true end def arity ARITY end def in_sequence_head [Node.new(:wildcard), self] end end # Node class for `<int str ...>` class AnyOrder < Node include ForbidInSeqHead ARITIES = Hash.new { |h, k| h[k] = (k - 1)..Float::INFINITY } private_constant :ARITIES def term_nodes ends_with_rest? ? children[0...-1] : children end def ends_with_rest? children.last.rest? end def rest_node children.last if ends_with_rest? end def arity return children.size unless ends_with_rest? ARITIES[children.size] end end # A list (potentially empty) of nodes; part of a Union class Subsequence < Node include ForbidInSeqHead def arity min, max = children.map { |child| child.arity_range.minmax }.transpose.map(&:sum) min == max ? min || 0 : min..max # NOTE: || 0 for empty case, where min == max == nil. end def in_sequence_head super if children.empty? return unless (replace = children.first.in_sequence_head) [with(children: [*replace, *children[1..]])] end end # Node class for `{ ... }` class Union < Node def arity minima, maxima = children.map { |child| child.arity_range.minmax }.transpose min = minima.min max = maxima.max min == max ? min : min..max end def in_sequence_head return unless children.any?(&:in_sequence_head) new_children = children.map do |child| next child unless (replace = child.in_sequence_head) if replace.size > 1 Subsequence.new(:subsequence, replace, loc: child.loc) else replace.first end end [with(children: new_children)] end # Each child in a union must contain the same number # of captures. Only one branch ends up capturing. def nb_captures child.nb_captures end end # Registry MAP = Hash.new(Node).merge!( sequence: Sequence, repetition: Repetition, rest: Rest, capture: Capture, predicate: Predicate, any_order: AnyOrder, function_call: FunctionCall, subsequence: Subsequence, union: Union ).freeze end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/method_definer.rb
lib/rubocop/ast/node_pattern/method_definer.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern # Functionality to turn `match_code` into methods/lambda module MethodDefiner def def_node_matcher(base, method_name, **defaults) def_helper(base, method_name, **defaults) do |name| params = emit_params('param0 = self') <<~RUBY def #{name}(#{params}) #{VAR} = param0 #{compile_init} #{emit_method_code} end RUBY end end def def_node_search(base, method_name, **defaults) def_helper(base, method_name, **defaults) do |name| emit_node_search(name) end end def compile_as_lambda <<~RUBY ->(#{emit_params('param0')}, block: nil) do #{VAR} = param0 #{compile_init} #{emit_lambda_code} end RUBY end def as_lambda eval(compile_as_lambda) # rubocop:disable Security/Eval end private # This method minimizes the closure for our method def wrapping_block(method_name, **defaults) proc do |*args, **values| send method_name, *args, **defaults, **values end end def def_helper(base, method_name, **defaults) location = caller_locations(3, 1).first unless defaults.empty? call = :"without_defaults_#{method_name}" base.send :define_method, method_name, &wrapping_block(call, **defaults) method_name = call end src = yield method_name base.class_eval(src, location.path, location.lineno) method_name end def emit_node_search(method_name) if method_name.to_s.end_with?('?') on_match = 'return true' else args = emit_params(":#{method_name}", 'param0', forwarding: true) prelude = "return enum_for(#{args}) unless block_given?\n" on_match = emit_yield_capture(VAR) end emit_node_search_body(method_name, prelude: prelude, on_match: on_match) end def emit_node_search_body(method_name, prelude:, on_match:) <<~RUBY def #{method_name}(#{emit_params('param0')}) #{compile_init} #{prelude} param0.each_node do |#{VAR}| if #{match_code} #{on_match} end end nil end RUBY end def emit_yield_capture(when_no_capture = '', yield_with: 'yield') yield_val = if captures.zero? when_no_capture elsif captures == 1 'captures[0]' # Circumvent https://github.com/jruby/jruby/issues/5710 else '*captures' end "#{yield_with}(#{yield_val})" end def emit_retval if captures.zero? 'true' elsif captures == 1 'captures[0]' else 'captures' end end def emit_param_list (1..positional_parameters).map { |n| "param#{n}" }.join(',') end def emit_keyword_list(forwarding: false) pattern = "%<keyword>s: #{'%<keyword>s' if forwarding}" named_parameters.map { |k| format(pattern, keyword: k) }.join(',') end def emit_params(*first, forwarding: false) params = emit_param_list keywords = emit_keyword_list(forwarding: forwarding) [*first, params, keywords].reject(&:empty?).join(',') end def emit_method_code <<~RUBY return unless #{match_code} block_given? ? #{emit_yield_capture} : (return #{emit_retval}) RUBY end def emit_lambda_code <<~RUBY return unless #{match_code} block ? #{emit_yield_capture(yield_with: 'block.call')} : (return #{emit_retval}) RUBY end def compile_init "captures = Array.new(#{captures})" if captures.positive? end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/parser.rb
lib/rubocop/ast/node_pattern/parser.rb
# frozen_string_literal: true require_relative 'parser.racc' module RuboCop module AST class NodePattern # Parser for NodePattern # Note: class reopened in `parser.racc` # # Doc on how this fits in the compiling process: # /docs/modules/ROOT/pages/node_pattern.adoc class Parser < Racc::Parser extend SimpleForwardable Builder = NodePattern::Builder Lexer = NodePattern::Lexer def initialize(builder = self.class::Builder.new) super() @builder = builder end ## # (Similar API to `parser` gem) # Parses a source and returns the AST. # # @param [Parser::Source::Buffer, String] source_buffer The source buffer to parse. # @return [NodePattern::Node] # def parse(source) @lexer = self.class::Lexer.new(source) do_parse rescue Lexer::Error => e raise NodePattern::Invalid, e.message ensure @lexer = nil # Don't keep references end def inspect "<##{self.class}>" end private def_delegators :@builder, :emit_list, :emit_unary_op, :emit_atom, :emit_capture, :emit_call, :emit_union def_delegators :@lexer, :next_token def enforce_unary(node) return node if node.arity == 1 detail = node.loc&.expression&.source || node.to_s raise NodePattern::Invalid, 'parse error, expected unary node pattern ' \ "but got expression matching multiple elements: #{detail}" end # Overrides Racc::Parser's method: def on_error(token, val, _vstack) detail = token_to_str(token) || '?' raise NodePattern::Invalid, "parse error on value #{val.inspect} (#{detail})" end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/comment.rb
lib/rubocop/ast/node_pattern/comment.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern # A NodePattern comment, simplified version of ::Parser::Source::Comment class Comment attr_reader :location alias loc location ## # @param [Parser::Source::Range] range # def initialize(range) @location = ::Parser::Source::Map.new(range) freeze end # @return [String] def text loc.expression.source.freeze end ## # Compares comments. Two comments are equal if they # correspond to the same source range. # # @param [Object] other # @return [Boolean] # def ==(other) other.is_a?(Comment) && @location == other.location end ## # @return [String] a human-readable representation of this comment # def inspect "#<NodePattern::Comment #{@location.expression} #{text.inspect}>" end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/lexer.rb
lib/rubocop/ast/node_pattern/lexer.rb
# frozen_string_literal: true begin require_relative 'lexer.rex' rescue LoadError msg = '*** You must run `rake generate` to generate the lexer and the parser ***' puts '*' * msg.length, msg, '*' * msg.length raise end module RuboCop module AST class NodePattern # Lexer class for `NodePattern` # # Doc on how this fits in the compiling process: # /docs/modules/ROOT/pages/node_pattern.adoc class Lexer < LexerRex Error = ScanError REGEXP_OPTIONS = { 'i' => ::Regexp::IGNORECASE, 'm' => ::Regexp::MULTILINE, 'x' => ::Regexp::EXTENDED, 'o' => 0 }.freeze private_constant :REGEXP_OPTIONS attr_reader :source_buffer, :comments, :tokens def initialize(source) @tokens = [] super() parse(source) end private # @return [token] def emit(type) value = ss[1] || ss.matched value = yield value if block_given? token = token(type, value) @tokens << token token end def emit_comment nil end def emit_regexp body = ss[1] options = ss[2] flag = options.each_char.sum { |c| REGEXP_OPTIONS[c] } emit(:tREGEXP) { Regexp.new(body, flag) } end def do_parse # Called by the generated `parse` method, do nothing here. end def token(type, value) [type, value] end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/builder.rb
lib/rubocop/ast/node_pattern/builder.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern # Responsible to build the AST nodes for `NodePattern` # # Doc on how this fits in the compiling process: # /docs/modules/ROOT/pages/node_pattern.adoc class Builder def emit_capture(capture_token, node) return node if capture_token.nil? emit_unary_op(:capture, capture_token, node) end def emit_atom(type, value) n(type, [value]) end def emit_unary_op(type, _operator = nil, *children) n(type, children) end def emit_list(type, _begin, children, _end) n(type, children) end def emit_call(type, selector, args = nil) _begin_t, arg_nodes, _end_t = args n(type, [selector, *arg_nodes]) end def emit_union(begin_t, pattern_lists, end_t) children = union_children(pattern_lists) type = optimizable_as_set?(children) ? :set : :union emit_list(type, begin_t, children, end_t) end def emit_subsequence(node_list) return node_list.first if node_list.size == 1 # Don't put a single child in a subsequence emit_list(:subsequence, nil, node_list, nil) end private def optimizable_as_set?(children) children.all?(&:matches_within_set?) end def n(type, *args) Node::MAP[type].new(type, *args) end def union_children(pattern_lists) if pattern_lists.size == 1 # {a b c} => [[a, b, c]] => [a, b, c] children = pattern_lists.first raise NodePattern::Invalid, 'A union can not be empty' if children.empty? children else # { a b | c } => [[a, b], [c]] => [s(:subsequence, a, b), c] pattern_lists.map do |list| emit_subsequence(list) end end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/compiler/subcompiler.rb
lib/rubocop/ast/node_pattern/compiler/subcompiler.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern class Compiler # Base class for subcompilers # Implements visitor pattern # # Doc on how this fits in the compiling process: # /docs/modules/ROOT/pages/node_pattern.adoc class Subcompiler attr_reader :compiler def initialize(compiler) @compiler = compiler @node = nil end def compile(node) prev = @node @node = node do_compile ensure @node = prev end # @api private private attr_reader :node def do_compile send(self.class.registry.fetch(node.type, :visit_other_type)) end @registry = {} class << self attr_reader :registry def method_added(method) @registry[Regexp.last_match(1).to_sym] = method if method =~ /^visit_(.*)/ super end def inherited(base) us = self base.class_eval { @registry = us.registry.dup } super end end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/compiler/node_pattern_subcompiler.rb
lib/rubocop/ast/node_pattern/compiler/node_pattern_subcompiler.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern class Compiler # Compiles code that evalues to true or false # for a given value `var` (typically a RuboCop::AST::Node) # or it's `node.type` if `seq_head` is true # # Doc on how this fits in the compiling process: # /docs/modules/ROOT/pages/node_pattern.adoc class NodePatternSubcompiler < Subcompiler attr_reader :access, :seq_head def initialize(compiler, var: nil, access: var, seq_head: false) super(compiler) @var = var @access = access @seq_head = seq_head end private def visit_negation expr = compile(node.child) "!(#{expr})" end def visit_ascend compiler.with_temp_variables do |ascend| expr = compiler.compile_as_node_pattern(node.child, var: ascend) "(#{ascend} = #{access_node}) && (#{ascend} = #{ascend}.parent) && #{expr}" end end def visit_descend compiler.with_temp_variables { |descendant| <<~RUBY.chomp } ::RuboCop::AST::NodePattern.descend(#{access}).any? do |#{descendant}| #{compiler.compile_as_node_pattern(node.child, var: descendant)} end RUBY end def visit_wildcard 'true' end def visit_unify name = compiler.bind(node.child) do |unify_name| # double assign to avoid "assigned but unused variable" return "(#{unify_name} = #{access_element}; #{unify_name} = #{unify_name}; true)" end compile_value_match(name) end def visit_capture "(#{compiler.next_capture} = #{access_element}; #{compile(node.child)})" end ### Lists def visit_union multiple_access(:union) do terms = compiler.each_union(node.children) .map { |child| compile(child) } "(#{terms.join(' || ')})" end end def visit_intersection multiple_access(:intersection) do node.children.map { |child| compile(child) } .join(' && ') end end def visit_predicate "#{access_element}.#{node.method_name}#{compile_args(node.arg_list)}" end def visit_function_call "#{node.method_name}#{compile_args(node.arg_list, first: access_element)}" end def visit_node_type "#{access_node}.#{node.child.to_s.tr('-', '_')}_type?" end def visit_sequence multiple_access(:sequence) do |var| term = compiler.compile_sequence(node, var: var) "#{compile_guard_clause} && #{term}" end end # Assumes other types are atoms. def visit_other_type value = compiler.compile_as_atom(node) compile_value_match(value) end # Compiling helpers def compile_value_match(value) "#{value} === #{access_element}" end # @param [Array<Node>, nil] # @return [String, nil] def compile_args(arg_list, first: nil) args = arg_list&.map { |arg| compiler.compile_as_atom(arg) } args = [first, *args] if first "(#{args.join(', ')})" if args end def access_element seq_head ? "#{access}.type" : access end def access_node return access if seq_head "#{compile_guard_clause} && #{access}" end def compile_guard_clause "#{access}.is_a?(::RuboCop::AST::Node)" end def multiple_access(kind) return yield @var if @var compiler.with_temp_variables(kind) do |var| memo = "#{var} = #{access}" @var = @access = var "(#{memo}; #{yield @var})" end end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/compiler/binding.rb
lib/rubocop/ast/node_pattern/compiler/binding.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern class Compiler # Holds the list of bound variable names class Binding def initialize @bound = {} end # Yields the first time a given name is bound # # @return [String] bound variable name def bind(name) var = @bound.fetch(name) do yield n = @bound[name] = "unify_#{name.gsub('-', '__')}" n end if var == :forbidden_unification raise Invalid, "Wildcard #{name} was first seen in a subset of a " \ "union and can't be used outside that union" end var end # Yields for each branch of the given union, forbidding unification of # bindings which only appear in a subset of the union. def union_bind(enum) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize # We need to reset @bound before each branch is processed. # Moreover we need to keep track of newly encountered wildcards. # Var `newly_bound_intersection` will hold those that are encountered # in all branches; these are not a problem. # Var `partially_bound` will hold those encountered in only a subset # of the branches; these can't be used outside of the union. return to_enum __method__, enum unless block_given? newly_bound_intersection = nil partially_bound = [] bound_before = @bound.dup result = enum.each do |e| @bound = bound_before.dup if newly_bound_intersection yield e newly_bound = @bound.keys - bound_before.keys if newly_bound_intersection.nil? # First iteration newly_bound_intersection = newly_bound else union = newly_bound_intersection | newly_bound newly_bound_intersection &= newly_bound partially_bound |= union - newly_bound_intersection end end # At this point, all members of `newly_bound_intersection` can be used # for unification outside of the union, but partially_bound may not forbid(partially_bound) result end private def forbid(names) names.each do |name| @bound[name] = :forbidden_unification end end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/compiler/debug.rb
lib/rubocop/ast/node_pattern/compiler/debug.rb
# frozen_string_literal: true require 'rainbow' module RuboCop module AST class NodePattern class Compiler # Variant of the Compiler with tracing information for nodes class Debug < Compiler # Compiled node pattern requires a named parameter `trace`, # which should be an instance of this class class Trace def initialize @visit = {} end # rubocop:disable Naming/PredicateMethod def enter(node_id) @visit[node_id] = false true end # rubocop:enable Naming/PredicateMethod def success(node_id) @visit[node_id] = true end # return nil (not visited), false (not matched) or true (matched) def matched?(node_id) @visit[node_id] end end attr_reader :node_ids # @api private class Colorizer COLOR_SCHEME = { not_visitable: :lightseagreen, nil => :yellow, false => :red, true => :green }.freeze # Result of a NodePattern run against a particular AST # Consider constructor is private Result = Struct.new(:colorizer, :trace, :returned, :ruby_ast) do # @return [String] a Rainbow colorized version of ruby def colorize(color_scheme = COLOR_SCHEME) map = color_map(color_scheme) ast.source_range.source_buffer.source.chars.map.with_index do |char, i| Rainbow(char).color(map[i]) end.join end # @return [Hash] a map for {character_position => color} def color_map(color_scheme = COLOR_SCHEME) @color_map ||= match_map .transform_values { |matched| color_scheme.fetch(matched) } .map { |node, color| color_map_for(node, color) } .inject(:merge) .tap { |h| h.default = color_scheme.fetch(:not_visitable) } end # @return [Hash] a map for {node => matched?}, depth-first def match_map @match_map ||= ast .each_node .to_h { |node| [node, matched?(node)] } end # @return a value of `Trace#matched?` or `:not_visitable` def matched?(node) id = colorizer.compiler.node_ids.fetch(node) { return :not_visitable } trace.matched?(id) end private def color_map_for(node, color) return {} unless (range = node.loc&.expression) range.to_a.to_h { |char| [char, color] } end def ast colorizer.node_pattern.ast end end Compiler = Debug attr_reader :pattern, :compiler, :node_pattern def initialize(pattern, compiler: self.class::Compiler.new) @pattern = pattern @compiler = compiler @node_pattern = ::RuboCop::AST::NodePattern.new(pattern, compiler: @compiler) end # @return [Node] the Ruby AST def test(ruby, trace: self.class::Compiler::Trace.new) ruby = ruby_ast(ruby) if ruby.is_a?(String) returned = @node_pattern.as_lambda.call(ruby, trace: trace) self.class::Result.new(self, trace, returned, ruby) end private def ruby_ast(ruby) ProcessedSource.new(ruby, RUBY_VERSION.to_f, '(ruby)').ast end end def initialize super @node_ids = Hash.new { |h, k| h[k] = h.size }.compare_by_identity end def named_parameters super << :trace end def parser @parser ||= Parser::WithMeta.new end def_delegators :parser, :comments, :tokens # @api private module InstrumentationSubcompiler def do_compile "#{tracer(:enter)} && #{super} && #{tracer(:success)}" end private def tracer(kind) "trace.#{kind}(#{node_id})" end def node_id compiler.node_ids[node] end end # @api private class NodePatternSubcompiler < Compiler::NodePatternSubcompiler include InstrumentationSubcompiler end # @api private class SequenceSubcompiler < Compiler::SequenceSubcompiler include InstrumentationSubcompiler end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/compiler/atom_subcompiler.rb
lib/rubocop/ast/node_pattern/compiler/atom_subcompiler.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern class Compiler # Generates code that evaluates to a value (Ruby object) # This value responds to `===`. # # Doc on how this fits in the compiling process: # /docs/modules/ROOT/pages/node_pattern.adoc class AtomSubcompiler < Subcompiler private def visit_unify compiler.bind(node.child) do raise Invalid, 'unified variables can not appear first as argument' end end def visit_symbol node.child.inspect end alias visit_number visit_symbol alias visit_string visit_symbol alias visit_regexp visit_symbol def visit_const node.child end def visit_named_parameter compiler.named_parameter(node.child) end def visit_positional_parameter compiler.positional_parameter(node.child) end def visit_set set = node.children.to_set(&:child).freeze NodePattern::Sets[set] end # Assumes other types are node patterns. def visit_other_type compiler.with_temp_variables do |compare| code = compiler.compile_as_node_pattern(node, var: compare) "->(#{compare}) { #{code} }" end end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/node_pattern/compiler/sequence_subcompiler.rb
lib/rubocop/ast/node_pattern/compiler/sequence_subcompiler.rb
# frozen_string_literal: true module RuboCop module AST class NodePattern class Compiler # Compiles terms within a sequence to code that evalues to true or false. # Compilation of the nodes that can match only a single term is deferred to # `NodePatternSubcompiler`; only nodes that can match multiple terms are # compiled here. # Assumes the given `var` is a `::RuboCop::AST::Node` # # Doc on how this fits in the compiling process: # /docs/modules/ROOT/pages/node_pattern.adoc # class SequenceSubcompiler < Subcompiler # rubocop:disable Metrics/ClassLength # Shift of 1 from standard Ruby indices DELTA = 1 POSITIVE = :positive?.to_proc private_constant :POSITIVE # Calls `compile_sequence`; the actual `compile` method # will be used for the different terms of the sequence. # The only case of re-entrant call to `compile` is `visit_capture` def initialize(compiler, sequence:, var:) @seq = sequence # The node to be compiled @seq_var = var # Holds the name of the variable holding the AST::Node we are matching super(compiler) end def compile_sequence # rubocop:disable Layout/CommentIndentation compiler.with_temp_variables do |cur_child, cur_index, previous_index| @cur_child_var = cur_child # To hold the current child node @cur_index_var = cur_index # To hold the current child index (always >= 0) @prev_index_var = previous_index # To hold the child index before we enter the # variadic nodes @cur_index = :seq_head # Can be any of: # :seq_head : when the current child is actually the # sequence head # :variadic_mode : child index held by @cur_index_var # >= 0 : when the current child index is known # (from the beginning) # < 0 : when the index is known from the end, # where -1 is *past the end*, # -2 is the last child, etc... # This shift of 1 from standard Ruby indices # is stored in DELTA @in_sync = false # `true` iff `@cur_child_var` and `@cur_index_var` # correspond to `@cur_index` # Must be true if `@cur_index` is `:variadic_mode` compile_terms end # rubocop:enable Layout/CommentIndentation end private private :compile # Not meant to be called from outside # Single node patterns are all handled here def visit_other_type access = case @cur_index when :seq_head { var: @seq_var, seq_head: true } when :variadic_mode { var: @cur_child_var } else idx = @cur_index + (@cur_index.negative? ? DELTA : 0) { access: "#{@seq_var}.children[#{idx}]" } end term = compiler.compile_as_node_pattern(node, **access) compile_and_advance(term) end def visit_repetition within_loop do child_captures = node.child.nb_captures child_code = compile(node.child) next compile_loop(child_code) if child_captures.zero? compile_captured_repetition(child_code, child_captures) end end def visit_any_order within_loop do compiler.with_temp_variables do |matched| case_terms = compile_any_order_branches(matched) else_code, init = compile_any_order_else term = "#{compile_case(case_terms, else_code)} && #{compile_loop_advance}" all_matched_check = "&&\n#{matched}.size == #{node.term_nodes.size}" if node.rest_node <<~RUBY (#{init}#{matched} = {}; true) && #{compile_loop(term)} #{all_matched_check} \\ RUBY end end end def visit_union return visit_other_type if node.arity == 1 # The way we implement complex unions is by "forking", i.e. # making a copy of the present subcompiler to compile each branch # of the union. # We then use the resulting state of the subcompilers to # reset ourselves. forks = compile_union_forks preserve_union_start(forks) merge_forks!(forks) expr = forks.values.join(" || \n") "(#{expr})" end def compile_case(when_branches, else_code) <<~RUBY case #{when_branches.join(' ')} else #{else_code} end \\ RUBY end def compile_any_order_branches(matched_var) node.term_nodes.map.with_index do |node, i| code = compiler.compile_as_node_pattern(node, var: @cur_child_var, seq_head: false) var = "#{matched_var}[#{i}]" "when !#{var} && #{code} then #{var} = true" end end # @return [Array<String>] Else code, and init code (if any) def compile_any_order_else rest = node.rest_node if !rest 'false' elsif rest.capture? capture_rest = compiler.next_capture init = "#{capture_rest} = [];" ["#{capture_rest} << #{@cur_child_var}", init] else 'true' end end def visit_capture return visit_other_type if node.child.arity == 1 storage = compiler.next_capture term = compile(node.child) capture = "#{@seq_var}.children[#{compile_matched(:range)}]" "#{term} && (#{storage} = #{capture})" end def visit_rest empty_loop end # Compilation helpers def compile_and_advance(term) case @cur_index when :variadic_mode "#{term} && #{compile_loop_advance}" when :seq_head # @in_sync = false # already the case @cur_index = 0 term else @in_sync = false @cur_index += 1 term end end def compile_captured_repetition(child_code, child_captures) captured_range = "#{compiler.captures - child_captures}...#{compiler.captures}" captured = "captures[#{captured_range}]" compiler.with_temp_variables do |accumulate| code = "#{child_code} && #{accumulate}.push(#{captured})" <<~RUBY (#{accumulate} = Array.new) && #{compile_loop(code)} && (#{captured} = if #{accumulate}.empty? (#{captured_range}).map{[]} # Transpose hack won't work for empty case else #{accumulate}.transpose end) \\ RUBY end end # Assumes `@cur_index` is already updated def compile_matched(kind) to = compile_cur_index from = if @prev_index == :variadic_mode @prev_index_used = true @prev_index_var else compile_index(@prev_index) end case kind when :range "#{from}...#{to}" when :length "#{to} - #{from}" end end def handle_prev @prev_index = @cur_index @prev_index_used = false code = yield if @prev_index_used @prev_index_used = false code = "(#{@prev_index_var} = #{@cur_index_var}; true) && #{code}" end code end def compile_terms(children = @seq.children, last_arity = 0..0) arities = remaining_arities(children, last_arity) total_arity = arities.shift guard = compile_child_nb_guard(total_arity) return guard if children.empty? @remaining_arity = total_arity terms = children.map do |child| use_index_from_end @remaining_arity = arities.shift handle_prev { compile(child) } end [guard, terms].join(" &&\n") end # yield `sync_code` iff not already in sync def sync return if @in_sync code = compile_loop_advance("= #{compile_cur_index}") @in_sync = true yield code end # @api private attr_reader :in_sync, :cur_index public :in_sync protected :cur_index, :compile_terms, :sync # @return [Array<Range>] total arities (as Ranges) of remaining children nodes # E.g. For sequence `(_ _? <_ _>)`, arities are: 1, 0..1, 2 # and remaining arities are: 3..4, 2..3, 2..2, 0..0 def remaining_arities(children, last_arity) last = last_arity arities = children .reverse .map(&:arity_range) .map { |r| last = (last.begin + r.begin)..(last.max + r.max) } .reverse! arities.push last_arity end # @return [String] code that evaluates to `false` if the matched arity is too small def compile_min_check return 'false' unless node.variadic? unless @remaining_arity.end.infinite? not_too_much_remaining = "#{compile_remaining} <= #{@remaining_arity.max}" end min_to_match = node.arity_range.begin if min_to_match.positive? enough_matched = "#{compile_matched(:length)} >= #{min_to_match}" end return 'true' unless not_too_much_remaining || enough_matched [not_too_much_remaining, enough_matched].compact.join(' && ') end def compile_remaining offset = case @cur_index when :seq_head ' + 1' when :variadic_mode " - #{@cur_index_var}" when 0 '' when POSITIVE " - #{@cur_index}" else # odd compiling condition, result may not be expected # E.g: `(... {a | b c})` => the b c branch can never match return - (@cur_index + DELTA) end "#{@seq_var}.children.size #{offset}" end def compile_max_matched return node.arity unless node.variadic? min_remaining_children = "#{compile_remaining} - #{@remaining_arity.begin}" return min_remaining_children if node.arity.end.infinite? "[#{min_remaining_children}, #{node.arity.max}].min" end def empty_loop @cur_index = -@remaining_arity.begin - DELTA @in_sync = false 'true' end def compile_cur_index return @cur_index_var if @in_sync compile_index end def compile_index(cur = @cur_index) return cur if cur >= 0 "#{@seq_var}.children.size - #{-(cur + DELTA)}" end # NOTE: assumes `@cur_index != :seq_head`. Node types using `within_loop` must # have `def in_sequence_head; :raise; end` def within_loop sync do |sync_code| @cur_index = :variadic_mode "#{sync_code} && #{yield}" end || yield end # returns truthy iff `@cur_index` switched to relative from end mode (i.e. < 0) def use_index_from_end return if @cur_index == :seq_head || @remaining_arity.begin != @remaining_arity.max @cur_index = -@remaining_arity.begin - DELTA end def compile_loop_advance(to = '+=1') # The `#{@cur_child_var} ||` is just to avoid unused variable warning "(#{@cur_child_var} = #{@seq_var}.children[#{@cur_index_var} #{to}]; " \ "#{@cur_child_var} || true)" end def compile_loop(term) <<~RUBY (#{compile_max_matched}).times do break #{compile_min_check} unless #{term} end \\ RUBY end def compile_child_nb_guard(arity_range) case arity_range.max when Float::INFINITY "#{compile_remaining} >= #{arity_range.begin}" when arity_range.begin "#{compile_remaining} == #{arity_range.begin}" else "(#{arity_range.begin}..#{arity_range.max}).cover?(#{compile_remaining})" end end # @return [Hash] of {subcompiler => code} def compile_union_forks compiler.each_union(node.children).to_h do |child| subsequence_terms = child.is_a?(Node::Subsequence) ? child.children : [child] fork = dup code = fork.compile_terms(subsequence_terms, @remaining_arity) @in_sync = false if @cur_index != :variadic_mode [fork, code] end end # Modifies in place `forks` to insure that `cur_{child|index}_var` are ok def preserve_union_start(forks) return if @cur_index != :variadic_mode || forks.size <= 1 compiler.with_temp_variables do |union_reset| cur = "(#{union_reset} = [#{@cur_child_var}, #{@cur_index_var}]) && " reset = "(#{@cur_child_var}, #{@cur_index_var} = #{union_reset}) && " forks.transform_values! do |code| code = "#{cur}#{code}" cur = reset code end end end # Modifies in place `forks` # Syncs our state def merge_forks!(forks) sub_compilers = forks.keys if !node.variadic? # e.g {a b | c d} @cur_index = sub_compilers.first.cur_index # all cur_index should be equivalent elsif use_index_from_end # nothing to do else # can't use index from end, so we must sync all forks @cur_index = :variadic_mode forks.each do |sub, code| sub.sync { |sync_code| forks[sub] = "#{code} && #{sync_code}" } end end @in_sync = sub_compilers.all?(&:in_sync) end end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/ext/range.rb
lib/rubocop/ast/ext/range.rb
# frozen_string_literal: true module RuboCop module AST module Ext # Extensions to Parser::AST::Range module Range # @return [Range] the range of line numbers for the node # If `exclude_end` is `true`, then the range will be exclusive. # # Assume that `node` corresponds to the following array literal: # # [ # :foo, # :bar # ] # # node.loc.begin.line_span # => 1..1 # node.source_range.line_span(exclude_end: true) # => 1...4 def line_span(exclude_end: false) ::Range.new(first_line, last_line, exclude_end) end end end end end Parser::Source::Range.include RuboCop::AST::Ext::Range
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
rubocop/rubocop-ast
https://github.com/rubocop/rubocop-ast/blob/69036498c11ca944c6099d1b672ba408f34a3eb4/lib/rubocop/ast/utilities/simple_forwardable.rb
lib/rubocop/ast/utilities/simple_forwardable.rb
# frozen_string_literal: true module RuboCop # Similar to `Forwardable#def_delegators`, but simpler & faster module SimpleForwardable def def_delegators(accessor, *methods) methods.each do |method| if method.end_with?('=') && method.to_s != '[]=' # Defining a delegator for `foo=` can't use `foo=(...)` because it is a # syntax error. Fall back to doing a slower `public_send` instead. # TODO: Use foo(method, ...) when Ruby 3.1 is required. class_eval(<<~RUBY, __FILE__, __LINE__ + 1) def #{method}(*args, **kwargs, &blk) # def example=(*args, **kwargs, &blk) #{accessor}.public_send(:#{method}, *args, **kwargs, &blk) # foo.public_send(:example=, *args, **kwargs, &blk) end # end RUBY else class_eval(<<~RUBY, __FILE__, __LINE__ + 1) def #{method}(...) # def example(...) #{accessor}.#{method}(...) # foo.example(...) end # end RUBY end end end end end
ruby
MIT
69036498c11ca944c6099d1b672ba408f34a3eb4
2026-01-04T17:49:41.556809Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true $LOAD_PATH.unshift File.expand_path('../lib', __dir__) # Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path('dummy/config/environment.rb', __dir__) ActiveRecord::Migrator.migrations_paths = [File.expand_path('dummy/db/migrate', __dir__)] ActiveRecord::Migration.maintain_test_schema! require "pry" require "rspec/rails" Dir[File.expand_path('support/**/*.rb', __dir__)].sort.each { |f| require f } RSpec.configure do |config| config.include Rack::Test::Methods config.fixture_path = File.expand_path('fixtures', __dir__) config.use_transactional_fixtures = true config.example_status_persistence_file_path = File.expand_path('../tmp/rspec-example-statuses.txt', __dir__) end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/support/pundit_stubs.rb
spec/support/pundit_stubs.rb
# frozen_string_literal: true module PunditStubs def allow_action(record, action) policy = ::Pundit::PolicyFinder.new(record).policy allow(policy).to( receive(:new).with(any_args, record) { instance_double(policy, action => true) } ) end def disallow_action(record, action) policy = ::Pundit::PolicyFinder.new(record).policy allow(policy).to( receive(:new).with(any_args, record) { instance_double(policy, action => false) } ) end def stub_policy_actions(record, actions_and_return_values) policy = ::Pundit::PolicyFinder.new(record).policy allow(policy).to( receive(:new).with(any_args, record) do instance_double(policy).tap do |policy_double| actions_and_return_values.each do |action, is_allowed| allow(policy_double).to receive(action).and_return(is_allowed) end end end ) end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/support/custom_matchers.rb
spec/support/custom_matchers.rb
# frozen_string_literal: true # Add better debuggability to be_forbidden failures RSpec::Matchers.define :be_forbidden do match(&:forbidden?) failure_message do |actual| debug_text_for_failure('forbidden', response: actual, last_request: last_request) end end # Add better debuggability to be_not_found failures RSpec::Matchers.define :be_not_found do match(&:not_found?) failure_message do |actual| debug_text_for_failure('not_found', response: actual, last_request: last_request) end end # Add better debuggability to be_unprocessable failures RSpec::Matchers.define :be_unprocessable do match(&:unprocessable?) failure_message do |actual| debug_text_for_failure('unprocessable', response: actual, last_request: last_request) end end # Add better debuggability to be_successful failures RSpec::Matchers.define :be_successful do match(&:successful?) failure_message do |actual| debug_text_for_failure('successful', response: actual, last_request: last_request) end end # Add better debuggability to be_ok failures RSpec::Matchers.define :be_ok do match(&:ok?) failure_message do |actual| debug_text_for_failure('ok', response: actual, last_request: last_request) end end def debug_text_for_failure(expected, response:, last_request:) debug_text = "expected response to be #{expected} but HTTP code was #{response.status}." debug_text += " Last request was #{last_request.request_method} to #{last_request.fullpath}" debug_text += " with body:\n#{last_request.body.read}" unless last_request.get? debug_text += "\nResponse body was:\n#{response.body}" debug_text end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/support/authorization_stubs.rb
spec/support/authorization_stubs.rb
# frozen_string_literal: true module AuthorizationStubs AUTHORIZER_CLASS = JSONAPI::Authorization::DefaultPunditAuthorizer def allow_operation(operation, authorizer: instance_double(AUTHORIZER_CLASS), **kwargs) allow(authorizer).to receive(operation).with(**kwargs).and_return(nil) allow(AUTHORIZER_CLASS).to receive(:new).with(context: kind_of(Hash)).and_return(authorizer) authorizer end def disallow_operation(operation, authorizer: instance_double(AUTHORIZER_CLASS), **kwargs) allow(authorizer).to receive(operation).with(**kwargs).and_raise(Pundit::NotAuthorizedError) allow(AUTHORIZER_CLASS).to receive(:new).with(context: kind_of(Hash)).and_return(authorizer) authorizer end def allow_operations(operation, operation_args) authorizer = instance_double(AUTHORIZER_CLASS) operation_args.each do |args| allow(authorizer).to receive(operation).with(*args).and_return(nil) end allow(AUTHORIZER_CLASS).to receive(:new).with(context: kind_of(Hash)).and_return(authorizer) end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/requests/resource_operations_spec.rb
spec/requests/resource_operations_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Resource operations', type: :request do include AuthorizationStubs fixtures :all let(:article) { Article.all.sample } let(:policy_scope) { Article.none } subject { last_response } let(:json_data) { JSON.parse(last_response.body)["data"] } before do allow_any_instance_of(ArticlePolicy::Scope).to receive(:resolve).and_return(policy_scope) end before do header 'Content-Type', 'application/vnd.api+json' end describe 'GET /articles' do subject(:last_response) { get('/articles') } context 'unauthorized for find' do before { disallow_operation('find', source_class: Article) } it { is_expected.to be_forbidden } end context 'authorized for find' do before { allow_operation('find', source_class: Article) } let(:policy_scope) { Article.where(id: article.id) } it { is_expected.to be_ok } it 'returns results limited by policy scope' do expect(json_data.length).to eq(1) expect(json_data.first["id"]).to eq(article.external_id) end end end describe 'GET /articles/:id' do subject(:last_response) { get("/articles/#{article.external_id}") } let(:policy_scope) { Article.all } context 'unauthorized for show' do before { disallow_operation('show', source_record: article) } context 'not limited by policy scope' do it { is_expected.to be_forbidden } end context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end context 'authorized for show' do before { allow_operation('show', source_record: article) } it { is_expected.to be_ok } # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end describe 'POST /articles' do subject(:last_response) { post("/articles", json) } let(:json) do <<-JSON.strip_heredoc { "data": { "id": "external_id", "type": "articles" } } JSON end context 'unauthorized for create_resource' do before { disallow_operation('create_resource', source_class: Article, related_records_with_context: []) } it { is_expected.to be_forbidden } end context 'authorized for create_resource' do before { allow_operation('create_resource', source_class: Article, related_records_with_context: []) } it { is_expected.to be_successful } end end describe 'PATCH /articles/:id' do let(:json) do <<-JSON.strip_heredoc { "data": { "id": "#{article.external_id}", "type": "articles" } } JSON end subject(:last_response) { patch("/articles/#{article.external_id}", json) } let(:policy_scope) { Article.all } context 'authorized for replace_fields' do before { allow_operation('replace_fields', source_record: article, related_records_with_context: []) } it { is_expected.to be_successful } context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end context 'unauthorized for replace_fields' do before { disallow_operation('replace_fields', source_record: article, related_records_with_context: []) } it { is_expected.to be_forbidden } context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end describe 'DELETE /articles/:id' do subject(:last_response) { delete("/articles/#{article.external_id}") } let(:policy_scope) { Article.all } context 'unauthorized for remove_resource' do before { disallow_operation('remove_resource', source_record: article) } context 'not limited by policy scope' do it { is_expected.to be_forbidden } end context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end context 'authorized for remove_resource' do before { allow_operation('remove_resource', source_record: article) } it { is_expected.to be_successful } # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/requests/tricky_operations_spec.rb
spec/requests/tricky_operations_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Tricky operations', type: :request do include AuthorizationStubs fixtures :all let(:article) { Article.all.sample } let(:policy_scope) { Article.none } subject { last_response } let(:json_data) { JSON.parse(last_response.body)["data"] } before do allow_any_instance_of(ArticlePolicy::Scope).to receive(:resolve).and_return(policy_scope) end before do header 'Content-Type', 'application/vnd.api+json' end describe 'POST /comments (with relationships link to articles)' do subject(:last_response) { post("/comments", json) } let(:json) do <<-JSON.strip_heredoc { "data": { "type": "comments", "relationships": { "article": { "data": { "id": "#{article.external_id}", "type": "articles" } } } } } JSON end let(:related_records_with_context) do [{ relation_name: :article, relation_type: :to_one, records: article }] end context 'authorized for create_resource on Comment and newly associated article' do let(:policy_scope) { Article.where(id: article.id) } before { allow_operation('create_resource', source_class: Comment, related_records_with_context: related_records_with_context) } it { is_expected.to be_successful } end context 'unauthorized for create_resource on Comment and newly associated article' do let(:policy_scope) { Article.where(id: article.id) } before { disallow_operation('create_resource', source_class: Comment, related_records_with_context: related_records_with_context) } it { is_expected.to be_forbidden } context 'which is out of scope' do let(:policy_scope) { Article.none } it { is_expected.to be_not_found } end end end describe 'POST /articles (with relationships link to comments)' do let!(:new_comments) do Array.new(2) { Comment.create } end let(:related_records_with_context) do [{ relation_name: :comments, relation_type: :to_many, records: new_comments }] end let(:comments_policy_scope) { Comment.all } before do allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return(comments_policy_scope) end let(:json) do <<-JSON.strip_heredoc { "data": { "id": "new-article-id", "type": "articles", "relationships": { "comments": { "data": [ { "id": "#{new_comments[0].id}", "type": "comments" }, { "id": "#{new_comments[1].id}", "type": "comments" } ] } } } } JSON end subject(:last_response) { post("/articles", json) } context 'authorized for create_resource on Article and newly associated comments' do let(:policy_scope) { Article.where(id: "new-article-id") } before { allow_operation('create_resource', source_class: Article, related_records_with_context: related_records_with_context) } it { is_expected.to be_successful } end context 'unauthorized for create_resource on Article and newly associated comments' do let(:policy_scope) { Article.where(id: "new-article-id") } before { disallow_operation('create_resource', source_class: Article, related_records_with_context: related_records_with_context) } it { is_expected.to be_forbidden } end end describe 'POST /tags (with polymorphic relationship link to article)' do subject(:last_response) { post("/tags", json) } let(:json) do <<-JSON.strip_heredoc { "data": { "type": "tags", "relationships": { "taggable": { "data": { "id": "#{article.external_id}", "type": "articles" } } } } } JSON end let(:related_records_with_context) do [{ relation_name: :taggable, relation_type: :to_one, records: article }] end context 'authorized for create_resource on Tag and newly associated article' do let(:policy_scope) { Article.where(id: article.id) } before { allow_operation('create_resource', source_class: Tag, related_records_with_context: related_records_with_context) } it { is_expected.to be_successful } end context 'unauthorized for create_resource on Tag and newly associated article' do let(:policy_scope) { Article.where(id: article.id) } before { disallow_operation('create_resource', source_class: Tag, related_records_with_context: related_records_with_context) } it { is_expected.to be_forbidden } context 'which is out of scope' do let(:policy_scope) { Article.none } it { is_expected.to be_not_found } end end end describe 'PATCH /articles/:id (mass-modifying relationships)' do let!(:new_comments) do Array.new(2) { Comment.create } end let(:related_records_with_context) do [{ relation_name: :comments, relation_type: :to_many, records: new_comments }] end let(:policy_scope) { Article.where(id: article.id) } let(:comments_policy_scope) { Comment.all } before do allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return(comments_policy_scope) end let(:json) do <<-JSON.strip_heredoc { "data": { "id": "#{article.external_id}", "type": "articles", "relationships": { "comments": { "data": [ { "type": "comments", "id": "#{new_comments.first.id}" }, { "type": "comments", "id": "#{new_comments.second.id}" } ] } } } } JSON end subject(:last_response) { patch("/articles/#{article.external_id}", json) } context 'authorized for replace_fields on article and all new records' do context 'not limited by Comments policy scope' do before { allow_operation('replace_fields', source_record: article, related_records_with_context: related_records_with_context) } it { is_expected.to be_successful } end context 'limited by Comments policy scope' do let(:comments_policy_scope) { Comment.where("id NOT IN (?)", new_comments.map(&:id)) } let(:related_records_with_context) do [{ relation_name: :comments, relation_type: :to_many, records: new_comments }] end before { disallow_operation('replace_fields', source_record: article, related_records_with_context: related_records_with_context) } it { is_expected.to be_not_found } end end context 'unauthorized for replace_fields on article and all new records' do before { disallow_operation('replace_fields', source_record: article, related_records_with_context: related_records_with_context) } it { is_expected.to be_forbidden } end end describe 'PATCH /articles/:id (nullifying to-one relationship)' do let(:article) { articles(:article_with_author) } let(:json) do <<-JSON.strip_heredoc { "data": { "id": "#{article.external_id}", "type": "articles", "relationships": { "author": null } } } JSON end let(:policy_scope) { Article.all } subject(:last_response) { patch("/articles/#{article.external_id}", json) } before do allow_operation( 'replace_fields', source_record: article, related_records_with_context: [{ relation_type: :to_one, relation_name: :author, records: nil }] ) end it { is_expected.to be_successful } end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/requests/relationship_operations_spec.rb
spec/requests/relationship_operations_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Relationship operations', type: :request do include AuthorizationStubs fixtures :all let(:article) { Article.all.sample } let(:policy_scope) { Article.none } let(:json_data) { JSON.parse(last_response.body)["data"] } before do allow_any_instance_of(ArticlePolicy::Scope).to receive(:resolve).and_return(policy_scope) end before do header 'Content-Type', 'application/vnd.api+json' end describe 'GET /articles/:id/relationships/comments' do let(:article) { articles(:article_with_comments) } let(:policy_scope) { Article.all } let(:comments_on_article) { article.comments } let(:comments_policy_scope) { comments_on_article.limit(1) } before do allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return(comments_policy_scope) end subject(:last_response) { get("/articles/#{article.external_id}/relationships/comments") } context 'unauthorized for show_relationship' do before { disallow_operation('show_relationship', source_record: article, related_record: nil) } it { is_expected.to be_forbidden } end context 'authorized for show_relationship' do before { allow_operation('show_relationship', source_record: article, related_record: nil) } it { is_expected.to be_ok } # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by ArticlePolicy::Scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end it 'displays only comments allowed by CommentPolicy::Scope' do expect(json_data.length).to eq(1) expect(json_data.first["id"]).to eq(comments_policy_scope.first.id.to_s) end end end describe 'GET /articles/:id/relationships/author' do subject(:last_response) { get("/articles/#{article.external_id}/relationships/author") } let(:article) { articles(:article_with_author) } let(:policy_scope) { Article.all } context 'unauthorized for show_relationship' do before { disallow_operation('show_relationship', source_record: article, related_record: article.author) } it { is_expected.to be_forbidden } end context 'authorized for show_relationship' do before { allow_operation('show_relationship', source_record: article, related_record: article.author) } it { is_expected.to be_ok } # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end describe 'POST /articles/:id/relationships/comments' do let(:new_comments) { Array.new(2) { Comment.new }.each(&:save) } let(:json) do <<-JSON.strip_heredoc { "data": [ { "type": "comments", "id": "#{new_comments.first.id}" }, { "type": "comments", "id": "#{new_comments.last.id}" } ] } JSON end subject(:last_response) { post("/articles/#{article.external_id}/relationships/comments", json) } let(:policy_scope) { Article.all } let(:comments_scope) { Comment.all } before do allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return(comments_scope) end context 'unauthorized for create_to_many_relationship' do before do disallow_operation( 'create_to_many_relationship', source_record: article, new_related_records: new_comments, relationship_type: :comments ) end it { is_expected.to be_forbidden } end context 'authorized for create_to_many_relationship' do before do allow_operation( 'create_to_many_relationship', source_record: article, new_related_records: new_comments, relationship_type: :comments ) end it { is_expected.to be_successful } context 'limited by policy scope on comments' do let(:comments_scope) { Comment.none } it { is_expected.to be_not_found } end # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope on articles' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end describe 'PATCH /articles/:id/relationships/comments' do let(:article) { articles(:article_with_comments) } let(:new_comments) { Array.new(2) { Comment.new }.each(&:save) } let(:json) do <<-JSON.strip_heredoc { "data": [ { "type": "comments", "id": "#{new_comments.first.id}" }, { "type": "comments", "id": "#{new_comments.last.id}" } ] } JSON end subject(:last_response) { patch("/articles/#{article.external_id}/relationships/comments", json) } let(:policy_scope) { Article.all } let(:comments_scope) { Comment.all } before do allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return(comments_scope) end context 'unauthorized for replace_to_many_relationship' do before do disallow_operation('replace_to_many_relationship', source_record: article, new_related_records: new_comments, relationship_type: :comments) end it { is_expected.to be_forbidden } end context 'authorized for replace_to_many_relationship' do context 'not limited by policy scopes' do before do allow_operation('replace_to_many_relationship', source_record: article, new_related_records: new_comments, relationship_type: :comments) end it { is_expected.to be_successful } end context 'limited by policy scope on comments' do let(:comments_scope) { Comment.none } before do allow_operation('replace_to_many_relationship', source_record: article, new_related_records: new_comments, relationship_type: :comments) end it do pending 'TODO: Maybe this actually should be succesful?' is_expected.to be_not_found end end # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope on articles' do before do allow_operation( 'replace_to_many_relationship', source_record: article, new_related_records: new_comments, relationship_type: :comments ) end let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end describe 'PATCH /articles/:id/relationships/author' do subject(:last_response) { patch("/articles/#{article.external_id}/relationships/author", json) } let(:article) { articles(:article_with_author) } let!(:old_author) { article.author } let(:policy_scope) { Article.all } let(:user_policy_scope) { User.all } before do allow_any_instance_of(UserPolicy::Scope).to receive(:resolve).and_return(user_policy_scope) end describe 'when replacing with a new author' do let(:new_author) { User.create } let(:json) do <<-JSON.strip_heredoc { "data": { "type": "users", "id": "#{new_author.id}" } } JSON end context 'unauthorized for replace_to_one_relationship' do before { disallow_operation('replace_to_one_relationship', source_record: article, new_related_record: new_author, relationship_type: :author) } it { is_expected.to be_forbidden } end context 'authorized for replace_to_one_relationship' do before { allow_operation('replace_to_one_relationship', source_record: article, new_related_record: new_author, relationship_type: :author) } it { is_expected.to be_successful } context 'limited by policy scope on author', skip: 'DISCUSS' do before do allow_any_instance_of(UserPolicy::Scope).to receive(:resolve).and_return(user_policy_scope) end let(:user_policy_scope) { User.where.not(id: article.author.id) } it { is_expected.to be_not_found } end # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope on article' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end describe 'when nullifying the author' do let(:new_author) { nil } let(:json) { '{ "data": null }' } context 'unauthorized for remove_to_one_relationship' do before { disallow_operation('remove_to_one_relationship', source_record: article, relationship_type: :author) } it { is_expected.to be_forbidden } end context 'authorized for remove_to_one_relationship' do before { allow_operation('remove_to_one_relationship', source_record: article, relationship_type: :author) } it { is_expected.to be_successful } context 'limited by policy scope on author', skip: 'DISCUSS' do let(:user_policy_scope) { User.where.not(id: article.author.id) } it { is_expected.to be_not_found } end # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope on article' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end end # Polymorphic has-one relationship replacing describe 'PATCH /tags/:id/relationships/taggable' do subject(:last_response) { patch("/tags/#{tag.id}/relationships/taggable", json) } let!(:old_taggable) { Comment.create } let!(:tag) { Tag.create(taggable: old_taggable) } let(:policy_scope) { Article.all } let(:comment_policy_scope) { Article.all } let(:tag_policy_scope) { Tag.all } before do allow_any_instance_of(TagPolicy::Scope).to receive(:resolve).and_return(tag_policy_scope) allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return(comment_policy_scope) end describe 'when replacing with a new taggable' do let!(:new_taggable) { Article.create(external_id: 'new-article-id') } let(:json) do <<-JSON.strip_heredoc { "data": { "type": "articles", "id": "#{new_taggable.external_id}" } } JSON end context 'unauthorized for replace_to_one_relationship' do before do disallow_operation( 'replace_to_one_relationship', source_record: tag, new_related_record: new_taggable, relationship_type: :taggable ) end it { is_expected.to be_forbidden } end context 'authorized for replace_to_one_relationship' do before do allow_operation( 'replace_to_one_relationship', source_record: tag, new_related_record: new_taggable, relationship_type: :taggable ) end it { is_expected.to be_successful } context 'limited by policy scope on taggable', skip: 'DISCUSS' do let(:policy_scope) { Article.where.not(id: tag.taggable.id) } it { is_expected.to be_not_found } end # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope on tag' do let(:tag_policy_scope) { Tag.where.not(id: tag.id) } it { is_expected.to be_not_found } end end end # https://github.com/cerebris/jsonapi-resources/issues/1081 describe 'when nullifying the taggable', skip: 'Broken upstream' do let(:new_taggable) { nil } let(:json) { '{ "data": null }' } context 'unauthorized for remove_to_one_relationship' do before { disallow_operation('remove_to_one_relationship', source_record: tag, relationship_type: :taggable) } it { is_expected.to be_forbidden } end context 'authorized for remove_to_one_relationship' do before { allow_operation('remove_to_one_relationship', source_record: tag, relationship_type: :taggable) } it { is_expected.to be_successful } context 'limited by policy scope on taggable', skip: 'DISCUSS' do let(:policy_scope) { Article.where.not(id: tag.taggable.id) } it { is_expected.to be_not_found } end # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope on tag' do let(:tag_policy_scope) { Tag.where.not(id: tag.id) } it { is_expected.to be_not_found } end end end end describe 'DELETE /articles/:id/relationships/comments' do let(:article) { articles(:article_with_comments) } let(:comments_to_remove) { article.comments.limit(2) } let(:json) do <<-JSON.strip_heredoc { "data": [ { "type": "comments", "id": "#{comments_to_remove.first.id}" }, { "type": "comments", "id": "#{comments_to_remove.last.id}" } ] } JSON end subject(:last_response) { delete("/articles/#{article.external_id}/relationships/comments", json) } let(:policy_scope) { Article.all } let(:comments_scope) { Comment.all } before do allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return(comments_scope) end context 'unauthorized for remove_to_many_relationship' do before do disallow_operation( 'remove_to_many_relationship', source_record: article, related_records: [comments_to_remove.first, comments_to_remove.second], relationship_type: :comments ) end it { is_expected.to be_forbidden } end context 'authorized for remove_to_many_relationship' do context 'not limited by policy scopes' do before do allow_operation( 'remove_to_many_relationship', source_record: article, related_records: [comments_to_remove.first, comments_to_remove.second], relationship_type: :comments ) end it { is_expected.to be_successful } end context 'limited by policy scope on comments' do let(:comments_scope) { Comment.none } before do disallow_operation('remove_to_many_relationship', source_record: article, related_records: comments_to_remove, relationship_type: :comments) end it { is_expected.to be_not_found } end # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope on articles' do before do allow_operation( 'remove_to_many_relationship', source_record: article, related_records: [comments_to_remove.first, comments_to_remove.second], relationship_type: :comments ) end let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end describe 'DELETE /articles/:id/relationships/author' do subject(:last_response) { delete("/articles/#{article.external_id}/relationships/author") } let(:article) { articles(:article_with_author) } let(:policy_scope) { Article.all } context 'unauthorized for remove_to_one_relationship' do before { disallow_operation('remove_to_one_relationship', source_record: article, relationship_type: :author) } it { is_expected.to be_forbidden } end context 'authorized for remove_to_one_relationship' do before { allow_operation('remove_to_one_relationship', source_record: article, relationship_type: :author) } it { is_expected.to be_successful } # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/requests/custom_name_relationship_operations_spec.rb
spec/requests/custom_name_relationship_operations_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'including custom name relationships', type: :request do include AuthorizationStubs fixtures :all subject { last_response } let(:json_included) { JSON.parse(last_response.body) } let(:comments_policy_scope) { Comment.all } before do allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return( comments_policy_scope ) allow_any_instance_of(CommentPolicy).to receive(:show?).and_return(true) allow_any_instance_of(UserPolicy).to receive(:show?).and_return(true) end before do header 'Content-Type', 'application/vnd.api+json' end describe 'GET /comments/:id/reviewer' do subject(:last_response) { get("/comments/#{Comment.first.id}/reviewer") } context "access authorized" do before do allow_any_instance_of(CommentPolicy).to receive(:show?).and_return(true) allow_any_instance_of(UserPolicy).to receive(:show?).and_return(true) end it { is_expected.to be_ok } end context "access to reviewer forbidden" do before do allow_any_instance_of(CommentPolicy).to receive(:show?).and_return(true) allow_any_instance_of(UserPolicy).to receive(:show?).and_return(false) end it { is_expected.to be_forbidden } end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/requests/related_resources_operations_spec.rb
spec/requests/related_resources_operations_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'Related resources operations', type: :request do include AuthorizationStubs fixtures :all let(:article) { Article.all.sample } let(:authorizations) { {} } let(:policy_scope) { Article.none } let(:user_policy_scope) { User.all } before do allow_any_instance_of(UserPolicy::Scope).to receive(:resolve).and_return(user_policy_scope) end let(:json_data) { JSON.parse(last_response.body)["data"] } before do allow_any_instance_of(ArticlePolicy::Scope).to receive(:resolve).and_return(policy_scope) end before do header 'Content-Type', 'application/vnd.api+json' end describe 'GET /articles/:id/comments' do subject(:last_response) { get("/articles/#{article.external_id}/comments") } let(:article) { articles(:article_with_comments) } let(:policy_scope) { Article.all } let(:comments_on_article) { article.comments } let(:comments_class) { comments_on_article.first.class } let(:comments_policy_scope) { comments_on_article.limit(1) } before do allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve).and_return(comments_policy_scope) end context 'unauthorized for show_related_resources' do before { disallow_operation('show_related_resources', source_record: article, related_record_class: comments_class) } it { is_expected.to be_forbidden } end context 'authorized for show_related_resources' do before { allow_operation('show_related_resources', source_record: article, related_record_class: comments_class) } it { is_expected.to be_ok } # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end it 'displays only comments allowed by CommentPolicy::Scope' do expect(json_data.length).to eq(1) expect(json_data.first["id"]).to eq(comments_policy_scope.first.id.to_s) end end end describe 'GET /articles/:id/author' do subject(:last_response) { get("/articles/#{article.external_id}/author") } let(:article) { articles(:article_with_author) } let(:policy_scope) { Article.all } context 'unauthorized for show_related_resource' do before { disallow_operation('show_related_resource', source_record: article, related_record: article.author) } it { is_expected.to be_forbidden } end context 'authorized for show_related_resource' do before { allow_operation('show_related_resource', source_record: article, related_record: article.author) } it { is_expected.to be_ok } # If this happens in real life, it's mostly a bug. We want to document the # behaviour in that case anyway, as it might be surprising. context 'limited by policy scope' do let(:policy_scope) { Article.where.not(id: article.id) } it { is_expected.to be_not_found } end end context 'authorized for show_related_resource while related resource is limited by policy scope' do # It might be surprising that with jsonapi-authorization that supports JR 0.9, the `related_record` # is indeed a real record here and not `nil`. If the policy scope was used, then the `related_record` # should be `nil` but alas, that is not the case. before { allow_operation('show_related_resource', source_record: article, related_record: article.author) } let(:user_policy_scope) { User.where.not(id: article.author.id) } it { is_expected.to be_ok } end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/requests/included_resources_spec.rb
spec/requests/included_resources_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'including resources alongside normal operations', type: :request do include AuthorizationStubs fixtures :all subject { last_response } let(:json_included) { JSON.parse(last_response.body)['included'] } let(:comments_policy_scope) { Comment.all } let(:article_policy_scope) { Article.all } let(:user_policy_scope) { User.all } # Take the stubbed scope and call merge(policy_scope.scope.all) so that the original # scope's conditions are not lost. Without it, the stub will always return all records # the user has access to regardless of context. before do allow_any_instance_of(ArticlePolicy::Scope).to receive(:resolve) do |policy_scope| article_policy_scope.merge(policy_scope.scope.all) end allow_any_instance_of(CommentPolicy::Scope).to receive(:resolve) do |policy_scope| comments_policy_scope.merge(policy_scope.scope.all) end allow_any_instance_of(UserPolicy::Scope).to receive(:resolve) do |policy_scope| user_policy_scope.merge(policy_scope.scope.all) end end before do header 'Content-Type', 'application/vnd.api+json' end shared_examples_for :include_directive_tests do describe 'one-level deep has_many relationship' do let(:include_query) { 'comments' } context 'unauthorized for include_has_many_resource for Comment' do before do disallow_operation( 'include_has_many_resource', source_record: an_instance_of(Article), record_class: Comment, authorizer: chained_authorizer ) end it { is_expected.to be_forbidden } end context 'authorized for include_has_many_resource for Comment' do before do allow_operation( 'include_has_many_resource', source_record: an_instance_of(Article), record_class: Comment, authorizer: chained_authorizer ) end it { is_expected.to be_successful } it 'includes only comments allowed by policy scope and associated with the article' do expect(json_included.length).to eq(article.comments.count) expect( json_included.map { |included| included["id"].to_i } ).to match_array(article.comments.map(&:id)) end end end describe 'one-level deep has_one relationship' do let(:include_query) { 'author' } context 'unauthorized for include_has_one_resource for article.author' do before do disallow_operation( 'include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer ) end it { is_expected.to be_forbidden } end context 'authorized for include_has_one_resource for article.author' do before do allow_operation( 'include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer ) end it { is_expected.to be_successful } it 'includes the associated author resource' do json_users = json_included.select { |i| i['type'] == 'users' } expect(json_users).to include(a_hash_including('id' => article.author.id.to_s)) end end end describe 'multiple one-level deep relationships' do let(:include_query) { 'author,comments' } context 'unauthorized for include_has_one_resource for article.author' do before do disallow_operation( 'include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer ) end it { is_expected.to be_forbidden } end context 'unauthorized for include_has_many_resource for Comment' do before do allow_operation('include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer) disallow_operation('include_has_many_resource', source_record: an_instance_of(Article), record_class: Comment, authorizer: chained_authorizer) end it { is_expected.to be_forbidden } end context 'authorized for both operations' do before do allow_operation('include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer) allow_operation('include_has_many_resource', source_record: an_instance_of(Article), record_class: Comment, authorizer: chained_authorizer) end it { is_expected.to be_successful } it 'includes only comments allowed by policy scope and associated with the article' do json_comments = json_included.select { |item| item['type'] == 'comments' } expect(json_comments.length).to eq(article.comments.count) expect( json_comments.map { |i| i['id'] } ).to match_array(article.comments.pluck(:id).map(&:to_s)) end it 'includes the associated author resource' do json_users = json_included.select { |item| item['type'] == 'users' } expect(json_users).to include(a_hash_including('id' => article.author.id.to_s)) end end end describe 'a deep relationship' do let(:include_query) { 'author.comments' } context 'unauthorized for first relationship' do before do disallow_operation( 'include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer ) end it { is_expected.to be_forbidden } end context 'authorized for first relationship' do before { allow_operation('include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer) } context 'unauthorized for second relationship' do before { disallow_operation('include_has_many_resource', source_record: an_instance_of(User), record_class: Comment, authorizer: chained_authorizer) } it { is_expected.to be_forbidden } end context 'authorized for second relationship' do before { allow_operation('include_has_many_resource', source_record: an_instance_of(User), record_class: Comment, authorizer: chained_authorizer) } it { is_expected.to be_successful } it 'includes the first level resource' do json_users = json_included.select { |item| item['type'] == 'users' } expect(json_users).to include(a_hash_including('id' => article.author.id.to_s)) end describe 'second level resources' do it 'includes only resources allowed by policy scope' do second_level_items = json_included.select { |item| item['type'] == 'comments' } expect(second_level_items.length).to eq(article.author.comments.count) expect( second_level_items.map { |i| i['id'] } ).to match_array(article.author.comments.pluck(:id).map(&:to_s)) end end end end end describe 'a deep relationship with empty relations' do context 'first level has_one is nil' do let(:include_query) { 'non-existing-article.comments' } it { is_expected.to be_successful } end context 'first level has_many is empty' do let(:include_query) { 'empty-articles.comments' } context 'unauthorized for first relationship' do before { disallow_operation('include_has_many_resource', source_record: an_instance_of(Article), record_class: Article, authorizer: chained_authorizer) } it { is_expected.to be_forbidden } end context 'authorized for first relationship' do before { allow_operation('include_has_many_resource', source_record: an_instance_of(Article), record_class: Article, authorizer: chained_authorizer) } it { is_expected.to be_successful } end end end end shared_examples_for :scope_limited_directive_tests do describe 'one-level deep has_many relationship' do let(:comments_policy_scope) { Comment.where(id: article.comments.first.id) } let(:include_query) { 'comments' } context 'authorized for include_has_many_resource for Comment' do before do allow_operation( 'include_has_many_resource', source_record: an_instance_of(Article), record_class: Comment, authorizer: chained_authorizer ) end it { is_expected.to be_successful } it 'includes only comments allowed by policy scope' do expect(json_included.length).to eq(comments_policy_scope.length) expect(json_included.first["id"]).to eq(comments_policy_scope.first.id.to_s) end end end describe 'multiple one-level deep relationships' do let(:include_query) { 'author,comments' } let(:comments_policy_scope) { Comment.where(id: article.comments.first.id) } context 'authorized for both operations' do before do allow_operation('include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer) allow_operation('include_has_many_resource', source_record: an_instance_of(Article), record_class: Comment, authorizer: chained_authorizer) end it { is_expected.to be_successful } it 'includes only comments allowed by policy scope and associated with the article' do json_comments = json_included.select { |item| item['type'] == 'comments' } expect(json_comments.length).to eq(comments_policy_scope.length) expect( json_comments.map { |i| i['id'] } ).to match_array(comments_policy_scope.pluck(:id).map(&:to_s)) end it 'includes the associated author resource' do json_users = json_included.select { |item| item['type'] == 'users' } expect(json_users).to include(a_hash_including('id' => article.author.id.to_s)) end end end describe 'a deep relationship' do let(:include_query) { 'author.comments' } let(:comments_policy_scope) { Comment.where(id: article.author.comments.first.id) } context 'authorized for first relationship' do before { allow_operation('include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer) } context 'authorized for second relationship' do before { allow_operation('include_has_many_resource', source_record: an_instance_of(User), record_class: Comment, authorizer: chained_authorizer) } it { is_expected.to be_successful } it 'includes the first level resource' do json_users = json_included.select { |item| item['type'] == 'users' } expect(json_users).to include(a_hash_including('id' => article.author.id.to_s)) end describe 'second level resources' do it 'includes only resources allowed by policy scope' do second_level_items = json_included.select { |item| item['type'] == 'comments' } expect(second_level_items.length).to eq(comments_policy_scope.length) expect( second_level_items.map { |i| i['id'] } ).to match_array(comments_policy_scope.pluck(:id).map(&:to_s)) end end end end end end shared_examples_for :scope_limited_directive_test_modify_relationships do describe 'one-level deep has_many relationship' do let(:comments_policy_scope) { Comment.where(id: existing_comments.first.id) } let(:include_query) { 'comments' } context 'authorized for include_has_many_resource for Comment' do before do allow_operation( 'include_has_many_resource', source_record: an_instance_of(Article), record_class: Comment, authorizer: chained_authorizer ) end it { is_expected.to be_not_found } end end describe 'multiple one-level deep relationships' do let(:include_query) { 'author,comments' } let(:comments_policy_scope) { Comment.where(id: existing_comments.first.id) } context 'authorized for both operations' do before do allow_operation('include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer) allow_operation('include_has_many_resource', source_record: an_instance_of(Article), record_class: Comment, authorizer: chained_authorizer) end it { is_expected.to be_not_found } end end describe 'a deep relationship' do let(:include_query) { 'author.comments' } let(:comments_policy_scope) { Comment.where(id: existing_author.comments.first.id) } context 'authorized for first relationship' do before { allow_operation('include_has_one_resource', source_record: an_instance_of(Article), related_record: an_instance_of(User), authorizer: chained_authorizer) } context 'authorized for second relationship' do before { allow_operation('include_has_many_resource', source_record: an_instance_of(User), record_class: Comment, authorizer: chained_authorizer) } it { is_expected.to be_not_found } end end end end describe 'GET /articles' do subject(:last_response) { get("/articles?include=#{include_query}") } let!(:chained_authorizer) { allow_operation('find', source_class: Article) } let(:article) do Article.create( external_id: "indifferent_external_id", author: User.create( comments: Array.new(2) { Comment.create } ), comments: Array.new(2) { Comment.create } ) end let(:article_policy_scope) { Article.where(id: article.id) } # TODO: Test properly with multiple articles, not just one. include_examples :include_directive_tests include_examples :scope_limited_directive_tests end describe 'GET /articles/:id' do let(:article) do Article.create( external_id: "indifferent_external_id", author: User.create( comments: Array.new(2) { Comment.create } ), comments: Array.new(2) { Comment.create } ) end subject(:last_response) { get("/articles/#{article.external_id}?include=#{include_query}") } let!(:chained_authorizer) { allow_operation('show', source_record: article) } include_examples :include_directive_tests include_examples :scope_limited_directive_tests end describe 'PATCH /articles/:id' do let(:article) do Article.create( external_id: "indifferent_external_id", author: User.create( comments: Array.new(2) { Comment.create } ), comments: Array.new(2) { Comment.create } ) end let(:attributes_json) { '{}' } let(:json) do <<-JSON.strip_heredoc { "data": { "type": "articles", "id": "#{article.external_id}", "attributes": #{attributes_json} } } JSON end subject(:last_response) { patch("/articles/#{article.external_id}?include=#{include_query}", json) } let!(:chained_authorizer) { allow_operation('replace_fields', source_record: article, related_records_with_context: []) } include_examples :include_directive_tests include_examples :scope_limited_directive_tests context 'the request has already failed validations' do let(:include_query) { 'author.comments' } let(:attributes_json) { '{ "blank-value": "indifferent" }' } it 'does not run include authorizations and fails with validation error' do expect(last_response).to be_unprocessable end end end describe 'POST /articles/:id' do let(:existing_author) do User.create( comments: Array.new(2) { Comment.create } ) end let(:existing_comments) do Array.new(2) { Comment.create } end let(:related_records_with_context) do [ { relation_type: :to_one, relation_name: :author, records: existing_author }, { relation_type: :to_many, relation_name: :comments, # Relax the constraints of expected records here. Lower level tests modify the # available policy scope for comments, so we will get a different amount of records deep # down in the other specs. # # This is fine, because we test resource create relationships with specific matcher records: kind_of(Enumerable) } ] end let(:attributes_json) { '{}' } let(:json) do <<-JSON.strip_heredoc { "data": { "type": "articles", "id": "indifferent_external_id", "attributes": #{attributes_json}, "relationships": { "comments": { "data": [ { "type": "comments", "id": "#{existing_comments.first.id}" }, { "type": "comments", "id": "#{existing_comments.second.id}" } ] }, "author": { "data": { "type": "users", "id": "#{existing_author.id}" } } } } } JSON end let(:article) { existing_author.articles.first } subject(:last_response) { post("/articles?include=#{include_query}", json) } let!(:chained_authorizer) do allow_operation( 'create_resource', source_class: Article, related_records_with_context: related_records_with_context ) end include_examples :include_directive_tests include_examples :scope_limited_directive_test_modify_relationships context 'the request has already failed validations' do let(:include_query) { 'author.comments' } let(:attributes_json) { '{ "blank-value": "indifferent" }' } it 'does not run include authorizations and fails with validation error' do expect(last_response).to be_unprocessable end end end describe 'GET /articles/:id/articles' do let(:article) do Article.create( external_id: "indifferent_external_id", author: User.create( comments: Array.new(2) { Comment.create } ), comments: Array.new(2) { Comment.create } ) end let(:article_policy_scope) { Article.where(id: article.id) } subject(:last_response) { get("/articles/#{article.external_id}/articles?include=#{include_query}") } let!(:chained_authorizer) { allow_operation('show_related_resources', source_record: article, related_record_class: article.class) } include_examples :include_directive_tests include_examples :scope_limited_directive_tests end describe 'GET /articles/:id/article' do let(:article) do Article.create( external_id: "indifferent_external_id", author: User.create( comments: Array.new(2) { Comment.create } ), comments: Array.new(2) { Comment.create } ) end subject(:last_response) { get("/articles/#{article.external_id}/article?include=#{include_query}") } let!(:chained_authorizer) { allow_operation('show_related_resource', source_record: article, related_record: article) } include_examples :include_directive_tests include_examples :scope_limited_directive_tests end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/jsonapi/authorization/configuration_spec.rb
spec/jsonapi/authorization/configuration_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe JSONAPI::Authorization::Configuration do after do # Set this back to the default after each JSONAPI::Authorization.configuration.pundit_user = :user end describe '#user_context' do context "given a symbol" do it "returns the 'user'" do JSONAPI::Authorization.configuration.pundit_user = :current_user user = User.new jsonapi_context = { current_user: user } user_context = JSONAPI::Authorization.configuration.user_context(jsonapi_context) expect(user_context).to be user end end context "given a proc" do it "returns the 'user'" do JSONAPI::Authorization.configuration.pundit_user = ->(context) { context[:current_user] } user = User.new jsonapi_context = { current_user: user } user_context = JSONAPI::Authorization.configuration.user_context(jsonapi_context) expect(user_context).to be user end end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/jsonapi/authorization/default_pundit_authorizer_spec.rb
spec/jsonapi/authorization/default_pundit_authorizer_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe JSONAPI::Authorization::DefaultPunditAuthorizer do include PunditStubs fixtures :all let(:source_record) { Article.new } let(:authorizer) { described_class.new(context: {}) } shared_examples_for :update_singular_fallback do |related_record_method| context 'authorized for update? on related record' do before { stub_policy_actions(send(related_record_method), update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for update? on related record' do before { stub_policy_actions(send(related_record_method), update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end shared_examples_for :update_multiple_fallback do |related_records_method| context 'authorized for update? on all related records' do before do send(related_records_method).each { |r| stub_policy_actions(r, update?: true) } end it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for update? on any related records' do before do stub_policy_actions(send(related_records_method).first, update?: false) end it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end describe '#find' do subject(:method_call) do authorizer.find(source_class: source_record) end context 'authorized for index? on record' do before { allow_action(source_record, 'index?') } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for index? on record' do before { disallow_action(source_record, 'index?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end describe '#show' do subject(:method_call) do authorizer.show(source_record: source_record) end context 'authorized for show? on record' do before { allow_action(source_record, 'show?') } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for show? on record' do before { disallow_action(source_record, 'show?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end describe '#show_relationship' do subject(:method_call) do authorizer.show_relationship( source_record: source_record, related_record: related_record ) end context 'authorized for show? on source record' do before { allow_action(source_record, 'show?') } context 'related record is present' do let(:related_record) { Comment.new } context 'authorized for show on related record' do before { allow_action(related_record, 'show?') } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for show on related record' do before { disallow_action(related_record, 'show?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end context 'related record is nil' do let(:related_record) { nil } it 'does not raise any errors' do expect { subject }.not_to raise_error end end end context 'unauthorized for show? on source record' do before { disallow_action(source_record, 'show?') } context 'related record is present' do let(:related_record) { Comment.new } context 'authorized for show on related record' do before { allow_action(related_record, 'show?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for show on related record' do before { disallow_action(related_record, 'show?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end context 'related record is nil' do let(:related_record) { nil } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe '#show_related_resource' do subject(:method_call) do authorizer.show_related_resource( source_record: source_record, related_record: related_record ) end context 'authorized for show? on source record' do before { allow_action(source_record, 'show?') } context 'related record is present' do let(:related_record) { Comment.new } context 'authorized for show on related record' do before { allow_action(related_record, 'show?') } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for show on related record' do before { disallow_action(related_record, 'show?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end context 'related record is nil' do let(:related_record) { nil } it 'does not raise any errors' do expect { subject }.not_to raise_error end end end context 'unauthorized for show? on source record' do before { disallow_action(source_record, 'show?') } context 'related record is present' do let(:related_record) { Comment.new } context 'authorized for show on related record' do before { allow_action(related_record, 'show?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for show on related record' do before { disallow_action(related_record, 'show?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end context 'related record is nil' do let(:related_record) { nil } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe '#show_related_resources' do let(:related_record) { Comment.new } subject(:method_call) do authorizer.show_related_resources(source_record: source_record, related_record_class: related_record) end context 'authorized for show? on source record' do before { allow_action(source_record, 'show?') } context 'authorized for index? on related record' do before { allow_action(related_record, 'index?') } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for index? on related record' do before { disallow_action(related_record, 'index?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end context 'unauthorized for show? on record' do before { disallow_action(source_record, 'show?') } context 'authorized for index? on related record' do before { allow_action(related_record, 'index?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for index? on related record' do before { disallow_action(related_record, 'index?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe '#replace_fields' do describe 'with "relation_type: :to_one"' do let(:related_record) { User.new } let(:related_records_with_context) do [{ relation_name: :author, relation_type: :to_one, records: related_record }] end subject(:method_call) do authorizer.replace_fields( source_record: source_record, related_records_with_context: related_records_with_context ) end context 'authorized for replace_<type>? and authorized for update? on source record' do before { stub_policy_actions(source_record, replace_author?: true, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for replace_<type>? and authorized for update? on source record' do before { stub_policy_actions(source_record, replace_author?: false, update?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for replace_<type>? and unauthorized for update? on source record' do before { stub_policy_actions(source_record, replace_author?: true, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for replace_<type>? and unauthorized for update? on source record' do before { stub_policy_actions(source_record, replace_author?: false, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where replace_<type>? is undefined' do context 'authorized for update? on source record' do before { stub_policy_actions(source_record, update?: true) } include_examples :update_singular_fallback, :related_record end context 'unauthorized for update? on source record' do before { stub_policy_actions(source_record, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe 'with "relation_type: :to_one" and records is nil' do let(:related_records_with_context) do [{ relation_name: :author, relation_type: :to_one, records: nil }] end subject(:method_call) do authorizer.replace_fields( source_record: source_record, related_records_with_context: related_records_with_context ) end context 'authorized for remove_<type>? and authorized for update? on source record' do before { stub_policy_actions(source_record, remove_author?: true, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for remove_<type>? and authorized for update? on source record' do before { stub_policy_actions(source_record, remove_author?: false, update?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for remove_<type>? and unauthorized for update? on source record' do before { stub_policy_actions(source_record, remove_author?: true, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for remove_<type>? and unauthorized for update? on source record' do before { stub_policy_actions(source_record, remove_author?: false, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where remove_<type>? is undefined' do context 'authorized for update? on source record' do before { stub_policy_actions(source_record, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for update? on source record' do before { stub_policy_actions(source_record, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe 'with "relation_type: :to_many"' do let(:related_records) { Array.new(3) { Comment.new } } let(:related_records_with_context) do [{ relation_name: :comments, relation_type: :to_many, records: related_records }] end subject(:method_call) do authorizer.replace_fields( source_record: source_record, related_records_with_context: related_records_with_context ) end context 'authorized for update? on source record and related records is empty' do before { allow_action(source_record, 'update?') } let(:related_records) { [] } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for update? on source record and related records is empty' do before { disallow_action(source_record, 'update?') } let(:related_records) { [] } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for replace_<type>? and authorized for update? on source record' do before { stub_policy_actions(source_record, replace_comments?: true, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for replace_<type>? and authorized for update? on source record' do before { stub_policy_actions(source_record, replace_comments?: false, update?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for replace_<type>? and unauthorized for update? on source record' do before { stub_policy_actions(source_record, replace_comments?: true, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for replace_<type>? and unauthorized for update? on source record' do before { stub_policy_actions(source_record, replace_comments?: false, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where replace_<type>? is undefined' do context 'authorized for update? on source record' do before { stub_policy_actions(source_record, update?: true) } include_examples :update_multiple_fallback, :related_records end context 'unauthorized for update? on source record' do before { stub_policy_actions(source_record, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end end describe '#create_resource' do describe 'with "relation_type: :to_one"' do let(:related_record) { User.new } let(:related_records_with_context) do [{ relation_name: :author, relation_type: :to_one, records: related_record }] end let(:source_class) { source_record.class } subject(:method_call) do authorizer.create_resource( source_class: source_class, related_records_with_context: related_records_with_context ) end context 'authorized for create? and authorized for create_with_<type>? on source class' do before { stub_policy_actions(source_class, create_with_author?: true, create?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'authorized for create? and unauthorized for create_with_<type>? on source class' do before { stub_policy_actions(source_class, create_with_author?: false, create?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for create? and authorized for create_with_<type>? on source class' do before { stub_policy_actions(source_class, create_with_author?: true, create?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for create? and unauthorized for create_with_<type>? on source class' do before { stub_policy_actions(source_class, create_with_author?: false, create?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where create_with_<type>? is undefined' do context 'authorized for create? on source class' do before { stub_policy_actions(source_class, create?: true) } include_examples :update_singular_fallback, :related_record end context 'unauthorized for create? on source class' do before { stub_policy_actions(source_class, create?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe 'with "relation_type: :to_many"' do let(:related_records) { Array.new(3) { Comment.new } } let(:related_records_with_context) do [{ relation_name: :comments, relation_type: :to_many, records: related_records }] end let(:source_class) { source_record.class } subject(:method_call) do authorizer.create_resource( source_class: source_class, related_records_with_context: related_records_with_context ) end context 'authorized for create? on source class and related records is empty' do before { stub_policy_actions(source_class, create?: true) } let(:related_records) { [] } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'authorized for create? and authorized for create_with_<type>? on source class' do before { stub_policy_actions(source_class, create_with_comments?: true, create?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'authorized for create? and unauthorized for create_with_<type>? on source class' do let(:related_records) { [Comment.new(id: 1), Comment.new(id: 2)] } before { stub_policy_actions(source_class, create_with_comments?: false, create?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for create? on source class and related records is empty' do let(:related_records) { [] } before { stub_policy_actions(source_class, create?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for create? and authorized for create_with_<type>? on source class' do before { stub_policy_actions(source_class, create_with_comments?: true, create?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'unauthorized for create? and unauthorized for create_with_<type>? on source class' do let(:related_records) { [Comment.new(id: 1), Comment.new(id: 2)] } before { stub_policy_actions(source_class, create_with_comments?: false, create?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where create_with_<type>? is undefined' do context 'authorized for create? on source class' do before { stub_policy_actions(source_class, create?: true) } include_examples :update_multiple_fallback, :related_records end context 'unauthorized for create? on source class' do before { stub_policy_actions(source_class, create?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end end describe '#remove_resource' do subject(:method_call) do authorizer.remove_resource(source_record: source_record) end context 'authorized for destroy? on record' do before { allow_action(source_record, 'destroy?') } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for destroy? on record' do before { disallow_action(source_record, 'destroy?') } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end describe '#replace_to_one_relationship' do let(:related_record) { User.new } subject(:method_call) do authorizer.replace_to_one_relationship( source_record: source_record, new_related_record: related_record, relationship_type: :author ) end context 'authorized for replace_<type>? and update? on record' do before { stub_policy_actions(source_record, replace_author?: true, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for replace_<type>? and authorized for update? on record' do before { stub_policy_actions(source_record, replace_author?: false, update?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for replace_<type>? and unauthorized for update? on record' do before { stub_policy_actions(source_record, replace_author?: true, update?: false) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for replace_<type>? and update? on record' do before { stub_policy_actions(source_record, replace_author?: false, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where replace_<type>? is undefined' do context 'authorized for update? on source record' do before { stub_policy_actions(source_record, update?: true) } include_examples :update_singular_fallback, :related_record end context 'unauthorized for update? on source record' do before { stub_policy_actions(source_record, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe '#create_to_many_relationship' do let(:related_records) { Array.new(3) { Comment.new } } subject(:method_call) do authorizer.create_to_many_relationship( source_record: source_record, new_related_records: related_records, relationship_type: :comments ) end context 'authorized for add_to_<type>? and update? on record' do before { stub_policy_actions(source_record, add_to_comments?: true, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for add_to_<type>? and authorized for update? on record' do before { stub_policy_actions(source_record, add_to_comments?: false, update?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for add_to_<type>? and unauthorized for update? on record' do before { stub_policy_actions(source_record, add_to_comments?: true, update?: false) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for add_to_<type>? and update? on record' do before { stub_policy_actions(source_record, add_to_comments?: false, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where add_to_<type>? not defined' do context 'authorized for update? on record' do before { stub_policy_actions(source_record, update?: true) } include_examples :update_multiple_fallback, :related_records end context 'unauthorized for update? on record' do before { stub_policy_actions(source_record, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe '#replace_to_many_relationship' do let(:article) { articles(:article_with_comments) } let(:new_comments) { Array.new(3) { Comment.new } } subject(:method_call) do authorizer.replace_to_many_relationship( source_record: article, new_related_records: new_comments, relationship_type: :comments ) end context 'authorized for replace_<type>? and update? on record' do before { stub_policy_actions(article, replace_comments?: true, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for replace_<type>? and authorized for update? on record' do before { stub_policy_actions(article, replace_comments?: false, update?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for replace_<type>? and unauthorized for update? on record' do before { stub_policy_actions(article, replace_comments?: true, update?: false) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for replace_<type>? and update? on record' do before { stub_policy_actions(article, replace_comments?: false, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where replace_<type>? not defined' do context 'authorized for update? on record' do before { stub_policy_actions(article, update?: true) } include_examples :update_multiple_fallback, :new_comments end context 'unauthorized for update? on record' do before { stub_policy_actions(article, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe '#remove_to_many_relationship' do let(:article) { articles(:article_with_comments) } let(:comments_to_remove) { article.comments.limit(2) } subject(:method_call) do authorizer.remove_to_many_relationship( source_record: article, related_records: comments_to_remove, relationship_type: :comments ) end context 'authorized for remove_from_<type>? and article? on article' do before { stub_policy_actions(article, remove_from_comments?: true, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for remove_from_<type>? and authorized for update? on article' do before { stub_policy_actions(article, remove_from_comments?: false, update?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for remove_from_<type>? and unauthorized for update? on article' do before { stub_policy_actions(article, remove_from_comments?: true, update?: false) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for remove_from_<type>? and update? on article' do before { stub_policy_actions(article, remove_from_comments?: false, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where remove_from_<type>? not defined' do context 'authorized for update? on article' do before { stub_policy_actions(article, update?: true) } include_examples :update_multiple_fallback, :comments_to_remove end context 'unauthorized for update? on article' do before { stub_policy_actions(article, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe '#remove_to_one_relationship' do subject(:method_call) do authorizer.remove_to_one_relationship( source_record: source_record, relationship_type: :author ) end context 'authorized for remove_<type>? and article? on record' do before { stub_policy_actions(source_record, remove_author?: true, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for remove_<type>? and authorized for update? on record' do before { stub_policy_actions(source_record, remove_author?: false, update?: true) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'authorized for remove_<type>? and unauthorized for update? on record' do before { stub_policy_actions(source_record, remove_author?: true, update?: false) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for remove_<type>? and update? on record' do before { stub_policy_actions(source_record, remove_author?: false, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end context 'where remove_<type>? not defined' do context 'authorized for update? on record' do before { stub_policy_actions(source_record, update?: true) } it 'does not raise any errors' do expect { subject }.not_to raise_error end end context 'unauthorized for update? on record' do before { stub_policy_actions(source_record, update?: false) } it 'raises a NotAuthorizedError' do expect { subject }.to raise_error(::Pundit::NotAuthorizedError) end end end end describe '#include_has_many_resource' do let(:record_class) { Article } let(:source_record) { Comment.new } subject(:method_call) do authorizer.include_has_many_resource( source_record: source_record, record_class: record_class ) end context 'authorized for index? on record class' do before { allow_action(record_class, 'index?') } it 'does not raise any errors' do
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
true
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/policies/comment_policy.rb
spec/dummy/app/policies/comment_policy.rb
# frozen_string_literal: true class CommentPolicy Scope = Struct.new(:user, :scope) do def resolve raise NotImplementedError end end attr_reader :user, :record def initialize(user, record) @user = user @record = record end def index? raise NotImplementedError end def show? raise NotImplementedError end def create? raise NotImplementedError end def update? raise NotImplementedError end def destroy? raise NotImplementedError end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/policies/article_policy.rb
spec/dummy/app/policies/article_policy.rb
# frozen_string_literal: true class ArticlePolicy Scope = Struct.new(:user, :scope) do def resolve raise NotImplementedError end end attr_reader :user, :record def initialize(user, record) @user = user @record = record end def index? raise NotImplementedError end def show? raise NotImplementedError end def create? raise NotImplementedError end def update? raise NotImplementedError end def destroy? raise NotImplementedError end def create_with_author?(_author) raise NotImplementedError end def create_with_comments?(_comments) raise NotImplementedError end def add_to_comments?(_comments) raise NotImplementedError end def replace_comments?(_comments) raise NotImplementedError end def remove_from_comments?(_comment) raise NotImplementedError end def replace_author?(_author) raise NotImplementedError end def remove_author? raise NotImplementedError end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/policies/user_policy.rb
spec/dummy/app/policies/user_policy.rb
# frozen_string_literal: true class UserPolicy Scope = Struct.new(:user, :scope) do def resolve raise NotImplementedError end end attr_reader :user, :record def initialize(user, record) @user = user @record = record end def index? raise NotImplementedError end def show? raise NotImplementedError end def create? raise NotImplementedError end def update? raise NotImplementedError end def destroy? raise NotImplementedError end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/policies/tag_policy.rb
spec/dummy/app/policies/tag_policy.rb
# frozen_string_literal: true class TagPolicy Scope = Struct.new(:user, :scope) do def resolve raise NotImplementedError end end attr_reader :user, :record def initialize(user, record) @user = user @record = record end def index? raise NotImplementedError end def show? raise NotImplementedError end def create? raise NotImplementedError end def update? raise NotImplementedError end def destroy? raise NotImplementedError end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/controllers/articles_controller.rb
spec/dummy/app/controllers/articles_controller.rb
# frozen_string_literal: true class ArticlesController < ApplicationController include JSONAPI::ActsAsResourceController rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized private def context { user: nil } end # https://github.com/cerebris/jsonapi-resources/pull/573 def handle_exceptions(err) if JSONAPI.configuration.exception_class_whitelist.any? { |k| err.class.ancestors.include?(k) } raise err end super end def user_not_authorized head :forbidden end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/controllers/taggable_controller.rb
spec/dummy/app/controllers/taggable_controller.rb
# frozen_string_literal: true # http://jsonapi-resources.com/v0.9/guide/resources.html#Relationships # # > The polymorphic relationship will require the resource # > and controller to exist, although routing to them will # > cause an error. class TaggablesController < JSONAPI::ResourceController; end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/controllers/tags_controller.rb
spec/dummy/app/controllers/tags_controller.rb
# frozen_string_literal: true class TagsController < ApplicationController include JSONAPI::ActsAsResourceController rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized private def context { user: nil } end # https://github.com/cerebris/jsonapi-resources/pull/573 def handle_exceptions(err) if JSONAPI.configuration.exception_class_whitelist.any? { |k| err.class.ancestors.include?(k) } raise err end super end def user_not_authorized head :forbidden end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/controllers/users_controller.rb
spec/dummy/app/controllers/users_controller.rb
# frozen_string_literal: true class UsersController < ApplicationController include JSONAPI::ActsAsResourceController rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized private def context { user: nil } end # https://github.com/cerebris/jsonapi-resources/pull/573 def handle_exceptions(err) if JSONAPI.configuration.exception_class_whitelist.any? { |k| err.class.ancestors.include?(k) } raise err end super end def user_not_authorized head :forbidden end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/controllers/comments_controller.rb
spec/dummy/app/controllers/comments_controller.rb
# frozen_string_literal: true class CommentsController < ApplicationController include JSONAPI::ActsAsResourceController rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized private def context { user: nil } end # https://github.com/cerebris/jsonapi-resources/pull/573 def handle_exceptions(err) if JSONAPI.configuration.exception_class_whitelist.any? { |k| err.class.ancestors.include?(k) } raise err end super end def user_not_authorized head :forbidden end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/controllers/application_controller.rb
spec/dummy/app/controllers/application_controller.rb
# frozen_string_literal: true class ApplicationController < ActionController::Base end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/models/tag.rb
spec/dummy/app/models/tag.rb
# frozen_string_literal: true class Tag < ActiveRecord::Base belongs_to :taggable, polymorphic: true end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/models/article.rb
spec/dummy/app/models/article.rb
# frozen_string_literal: true class Article < ActiveRecord::Base has_many :comments has_many :tags, as: :taggable belongs_to :author, class_name: 'User' def to_param external_id end # Hack for easy include directive checks has_many :articles, -> { limit(2) }, foreign_key: :id has_one :article, foreign_key: :id has_one :non_existing_article, -> { none }, class_name: 'Article', foreign_key: :id has_many :empty_articles, -> { none }, class_name: 'Article', foreign_key: :id # Setting blank_value attribute is an easy way to test that authorizations # work even when the model has validation errors validate :blank_value_must_be_blank private def blank_value_must_be_blank errors.add(:blank_value, 'must be blank') unless blank_value.blank? end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/models/comment.rb
spec/dummy/app/models/comment.rb
# frozen_string_literal: true class Comment < ActiveRecord::Base has_many :tags, as: :taggable belongs_to :article belongs_to :author, class_name: 'User' belongs_to :reviewing_user, class_name: 'User' end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/models/user.rb
spec/dummy/app/models/user.rb
# frozen_string_literal: true class User < ActiveRecord::Base has_many :articles, foreign_key: :author_id has_many :comments, foreign_key: :author_id end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/resources/comment_resource.rb
spec/dummy/app/resources/comment_resource.rb
# frozen_string_literal: true class CommentResource < JSONAPI::Resource include JSONAPI::Authorization::PunditScopedResource has_many :tags has_one :article has_one :reviewer, relation_name: "reviewing_user", class_name: "User" end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/resources/user_resource.rb
spec/dummy/app/resources/user_resource.rb
# frozen_string_literal: true class UserResource < JSONAPI::Resource include JSONAPI::Authorization::PunditScopedResource has_many :comments end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/resources/tag_resource.rb
spec/dummy/app/resources/tag_resource.rb
# frozen_string_literal: true class TagResource < JSONAPI::Resource include JSONAPI::Authorization::PunditScopedResource has_one :taggable, polymorphic: true end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/resources/taggable_resource.rb
spec/dummy/app/resources/taggable_resource.rb
# frozen_string_literal: true # http://jsonapi-resources.com/v0.9/guide/resources.html#Relationships # # > The polymorphic relationship will require the resource # > and controller to exist, although routing to them will # > cause an error. class TaggableResource < JSONAPI::Resource def self.verify_key(key, _context = nil) # Allow a string key for polymorphic associations key && String(key) end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/app/resources/article_resource.rb
spec/dummy/app/resources/article_resource.rb
# frozen_string_literal: true class ArticleResource < JSONAPI::Resource include JSONAPI::Authorization::PunditScopedResource has_many :comments, acts_as_set: true has_many :tags has_one :author, class_name: 'User' primary_key :external_id def self.verify_key(key, _context = nil) key && String(key) end def id=(external_id) _model.external_id = external_id end # # Hack for easy include directive checks has_many :articles has_one :article has_one :non_existing_article, class_name: 'Article', foreign_key_on: :related has_many :empty_articles, class_name: 'Article', foreign_key_on: :related # Setting this attribute is an easy way to test that authorizations work even # when the model has validation errors attributes :blank_value def self.creatable_fields(context) super + [:id] end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/db/schema.rb
spec/dummy/db/schema.rb
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20160125083537) do create_table "articles", force: :cascade do |t| t.string "external_id", null: false t.integer "author_id" t.string "blank_value" end create_table "comments", force: :cascade do |t| t.string "article_id" t.integer "author_id" t.integer "reviewing_user_id" end create_table "tags", force: :cascade do |t| t.integer "taggable_id" t.string "taggable_type" end create_table "users", force: :cascade do |t| end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/db/migrate/20160125083537_create_models.rb
spec/dummy/db/migrate/20160125083537_create_models.rb
# frozen_string_literal: true class CreateModels < ActiveRecord::Migration def change create_table :comments do |t| t.string :article_id t.belongs_to :author t.belongs_to :reviewing_user, references: :user end create_table :users create_table :articles do |t| t.string :external_id, null: false t.references :author t.string :blank_value end create_table :tags do |t| t.references :taggable, polymorphic: true end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/config/application.rb
spec/dummy/config/application.rb
# frozen_string_literal: true require File.expand_path('boot', __dir__) require "rails/all" Bundler.require(:default, Rails.env) class Application < Rails::Application config.root = File.expand_path('..', __dir__) config.cache_classes = true config.eager_load = false config.serve_static_files = true config.static_cache_control = "public, max-age=3600" config.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_dispatch.show_exceptions = false config.action_controller.allow_forgery_protection = false config.active_support.deprecation = :stderr config.middleware.delete "Rack::Lock" config.middleware.delete "ActionDispatch::Flash" # config.middleware.delete "ActionDispatch::BestStandardsSupport" config.secret_key_base = "correct-horse-battery-staple" end JSONAPI.configure do |config| config.default_processor_klass = JSONAPI::Authorization::AuthorizingProcessor config.exception_class_whitelist = [Pundit::NotAuthorizedError] end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/config/environment.rb
spec/dummy/config/environment.rb
# frozen_string_literal: true # Load the Rails application. require File.expand_path('application', __dir__) # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/config/routes.rb
spec/dummy/config/routes.rb
# frozen_string_literal: true Rails.application.routes.draw do jsonapi_resources :articles do jsonapi_relationships end jsonapi_resources :comments do jsonapi_relationships end jsonapi_resources :tags end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/spec/dummy/config/boot.rb
spec/dummy/config/boot.rb
# frozen_string_literal: true # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) $LOAD_PATH.unshift File.expand_path('../../../lib', __dir__)
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/lib/jsonapi-authorization.rb
lib/jsonapi-authorization.rb
# frozen_string_literal: true require 'jsonapi/authorization'
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/lib/jsonapi/authorization.rb
lib/jsonapi/authorization.rb
# frozen_string_literal: true require "jsonapi-resources" require "jsonapi/authorization/authorizing_processor" require "jsonapi/authorization/configuration" require "jsonapi/authorization/default_pundit_authorizer" require "jsonapi/authorization/pundit_scoped_resource" require "jsonapi/authorization/version" module JSONAPI module Authorization # Your code goes here... end end # Allows JSONAPI configuration of operations_processor using the symbol :jsonapi_authorization JsonapiAuthorizationProcessor = JSONAPI::Authorization::AuthorizingProcessor
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/lib/jsonapi/authorization/version.rb
lib/jsonapi/authorization/version.rb
# frozen_string_literal: true module JSONAPI module Authorization VERSION = "3.0.2" end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/lib/jsonapi/authorization/default_pundit_authorizer.rb
lib/jsonapi/authorization/default_pundit_authorizer.rb
# frozen_string_literal: true module JSONAPI module Authorization # An authorizer is a class responsible for linking JSONAPI operations to # your choice of authorization mechanism. # # This class uses Pundit for authorization. You can use your own authorizer # class instead if you have different needs. See the README.md for # configuration information. # # Fetching records is the concern of +PunditScopedResource+ which in turn # affects which records end up being passed here. class DefaultPunditAuthorizer attr_reader :user # Creates a new DefaultPunditAuthorizer instance # # ==== Parameters # # * +context+ - The context passed down from the controller layer def initialize(context:) @user = JSONAPI::Authorization.configuration.user_context(context) end # <tt>GET /resources</tt> # # ==== Parameters # # * +source_class+ - The source class (e.g. +Article+ for +ArticleResource+) def find(source_class:) ::Pundit.authorize(user, source_class, 'index?') end # <tt>GET /resources/:id</tt> # # ==== Parameters # # * +source_record+ - The record to show def show(source_record:) ::Pundit.authorize(user, source_record, 'show?') end # <tt>GET /resources/:id/relationships/other-resources</tt> # <tt>GET /resources/:id/relationships/another-resource</tt> # # A query for a +has_one+ or a +has_many+ association # # ==== Parameters # # * +source_record+ - The record whose relationship is queried # * +related_record+ - The associated +has_one+ record to show or +nil+ # if the associated record was not found. For a +has_many+ association, # this will always be +nil+ def show_relationship(source_record:, related_record:) ::Pundit.authorize(user, source_record, 'show?') ::Pundit.authorize(user, related_record, 'show?') unless related_record.nil? end # <tt>GET /resources/:id/another-resource</tt> # # A query for a record through a +has_one+ association # # ==== Parameters # # * +source_record+ - The record whose relationship is queried # * +related_record+ - The associated record to show or +nil+ if the # associated record was not found def show_related_resource(source_record:, related_record:) ::Pundit.authorize(user, source_record, 'show?') ::Pundit.authorize(user, related_record, 'show?') unless related_record.nil? end # <tt>GET /resources/:id/other-resources</tt> # # A query for records through a +has_many+ association # # ==== Parameters # # * +source_record+ - The record whose relationship is queried # * +related_record_class+ - The associated record class to show def show_related_resources(source_record:, related_record_class:) ::Pundit.authorize(user, source_record, 'show?') ::Pundit.authorize(user, related_record_class, 'index?') end # <tt>PATCH /resources/:id</tt> # # ==== Parameters # # * +source_record+ - The record to be modified # * +related_records_with_context+ - A hash with the association type, # the relationship name, an Array of new related records. def replace_fields(source_record:, related_records_with_context:) ::Pundit.authorize(user, source_record, 'update?') authorize_related_records( source_record: source_record, related_records_with_context: related_records_with_context ) end # <tt>POST /resources</tt> # # ==== Parameters # # * +source_class+ - The class of the record to be created # * +related_records_with_context+ - A has with the association type, # the relationship name, and an Array of new related records. def create_resource(source_class:, related_records_with_context:) ::Pundit.authorize(user, source_class, 'create?') related_records_with_context.each do |data| relation_name = data[:relation_name] records = data[:records] relationship_method = "create_with_#{relation_name}?" policy = ::Pundit.policy(user, source_class) if policy.respond_to?(relationship_method) unless policy.public_send(relationship_method, records) raise ::Pundit::NotAuthorizedError, query: relationship_method, record: source_class, policy: policy end else Array(records).each do |record| ::Pundit.authorize(user, record, 'update?') end end end end # <tt>DELETE /resources/:id</tt> # # ==== Parameters # # * +source_record+ - The record to be removed def remove_resource(source_record:) ::Pundit.authorize(user, source_record, 'destroy?') end # <tt>PATCH /resources/:id/relationships/another-resource</tt> # # A replace request for a +has_one+ association # # ==== Parameters # # * +source_record+ - The record whose relationship is modified # * +new_related_record+ - The new record replacing the old record # * +relationship_type+ - The relationship type def replace_to_one_relationship(source_record:, new_related_record:, relationship_type:) relationship_method = "replace_#{relationship_type}?" authorize_relationship_operation( source_record: source_record, relationship_method: relationship_method, related_record_or_records: new_related_record ) end # <tt>POST /resources/:id/relationships/other-resources</tt> # # A request for adding to a +has_many+ association # # ==== Parameters # # * +source_record+ - The record whose relationship is modified # * +new_related_records+ - The new records to be added to the association # * +relationship_type+ - The relationship type def create_to_many_relationship(source_record:, new_related_records:, relationship_type:) relationship_method = "add_to_#{relationship_type}?" authorize_relationship_operation( source_record: source_record, relationship_method: relationship_method, related_record_or_records: new_related_records ) end # <tt>PATCH /resources/:id/relationships/other-resources</tt> # # A replace request for a +has_many+ association # # ==== Parameters # # * +source_record+ - The record whose relationship is modified # * +new_related_records+ - The new records replacing the entire +has_many+ # association # * +relationship_type+ - The relationship type def replace_to_many_relationship(source_record:, new_related_records:, relationship_type:) relationship_method = "replace_#{relationship_type}?" authorize_relationship_operation( source_record: source_record, relationship_method: relationship_method, related_record_or_records: new_related_records ) end # <tt>DELETE /resources/:id/relationships/other-resources</tt> # # A request to disassociate elements of a +has_many+ association # # ==== Parameters # # * +source_record+ - The record whose relationship is modified # * +related_records+ - The records which will be disassociated from +source_record+ # * +relationship_type+ - The relationship type def remove_to_many_relationship(source_record:, related_records:, relationship_type:) relationship_method = "remove_from_#{relationship_type}?" authorize_relationship_operation( source_record: source_record, relationship_method: relationship_method, related_record_or_records: related_records ) end # <tt>DELETE /resources/:id/relationships/another-resource</tt> # # A request to disassociate a +has_one+ association # # ==== Parameters # # * +source_record+ - The record whose relationship is modified # * +relationship_type+ - The relationship type def remove_to_one_relationship(source_record:, relationship_type:) relationship_method = "remove_#{relationship_type}?" authorize_relationship_operation( source_record: source_record, relationship_method: relationship_method ) end # Any request including <tt>?include=other-resources</tt> # # This will be called for each has_many relationship if the include goes # deeper than one level until some authorization fails or the include # directive has been travelled completely. # # We can't pass all the records of a +has_many+ association here due to # performance reasons, so the class is passed instead. # # ==== Parameters # # * +source_record+ — The source relationship record, e.g. an Article in # article.comments check # * +record_class+ - The underlying record class for the relationships # resource. # rubocop:disable Lint/UnusedMethodArgument def include_has_many_resource(source_record:, record_class:) ::Pundit.authorize(user, record_class, 'index?') end # rubocop:enable Lint/UnusedMethodArgument # Any request including <tt>?include=another-resource</tt> # # This will be called for each has_one relationship if the include goes # deeper than one level until some authorization fails or the include # directive has been travelled completely. # # ==== Parameters # # * +source_record+ — The source relationship record, e.g. an Article in # article.author check # * +related_record+ - The associated record to return # rubocop:disable Lint/UnusedMethodArgument def include_has_one_resource(source_record:, related_record:) ::Pundit.authorize(user, related_record, 'show?') end # rubocop:enable Lint/UnusedMethodArgument private def authorize_relationship_operation( source_record:, relationship_method:, related_record_or_records: nil ) policy = ::Pundit.policy(user, source_record) if policy.respond_to?(relationship_method) args = [relationship_method, related_record_or_records].compact unless policy.public_send(*args) raise ::Pundit::NotAuthorizedError, query: relationship_method, record: source_record, policy: policy end else ::Pundit.authorize(user, source_record, 'update?') if related_record_or_records Array(related_record_or_records).each do |related_record| ::Pundit.authorize(user, related_record, 'update?') end end end end def authorize_related_records(source_record:, related_records_with_context:) related_records_with_context.each do |data| relation_type = data[:relation_type] relation_name = data[:relation_name] records = data[:records] case relation_type when :to_many replace_to_many_relationship( source_record: source_record, new_related_records: records, relationship_type: relation_name ) when :to_one if records.nil? remove_to_one_relationship( source_record: source_record, relationship_type: relation_name ) else replace_to_one_relationship( source_record: source_record, new_related_record: records, relationship_type: relation_name ) end end end end end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/lib/jsonapi/authorization/authorizing_processor.rb
lib/jsonapi/authorization/authorizing_processor.rb
# frozen_string_literal: true require 'pundit' module JSONAPI module Authorization class AuthorizingProcessor < JSONAPI::Processor set_callback :find, :before, :authorize_find set_callback :show, :before, :authorize_show set_callback :show_relationship, :before, :authorize_show_relationship set_callback :show_related_resource, :before, :authorize_show_related_resource set_callback :show_related_resources, :before, :authorize_show_related_resources set_callback :create_resource, :before, :authorize_create_resource set_callback :remove_resource, :before, :authorize_remove_resource set_callback :replace_fields, :before, :authorize_replace_fields set_callback :replace_to_one_relationship, :before, :authorize_replace_to_one_relationship set_callback :remove_to_one_relationship, :before, :authorize_remove_to_one_relationship set_callback :create_to_many_relationships, :before, :authorize_create_to_many_relationships set_callback :replace_to_many_relationships, :before, :authorize_replace_to_many_relationships set_callback :remove_to_many_relationships, :before, :authorize_remove_to_many_relationships set_callback( :replace_polymorphic_to_one_relationship, :before, :authorize_replace_polymorphic_to_one_relationship ) %i[ find show show_related_resource show_related_resources create_resource replace_fields ].each do |op_name| set_callback op_name, :after, :authorize_include_directive end def authorize_include_directive return if result.is_a?(::JSONAPI::ErrorsOperationResult) resources = Array.wrap( if result.respond_to?(:resources) result.resources elsif result.respond_to?(:resource) result.resource end ) resources.each do |resource| authorize_model_includes(resource._model) end end def authorize_find authorizer.find(source_class: @resource_klass._model_class) end def authorize_show record = @resource_klass.find_by_key( operation_resource_id, context: context )._model authorizer.show(source_record: record) end def authorize_show_relationship parent_resource = @resource_klass.find_by_key( params[:parent_key], context: context ) relationship = @resource_klass._relationship(params[:relationship_type].to_sym) related_resource = case relationship when JSONAPI::Relationship::ToOne parent_resource.public_send(params[:relationship_type].to_sym) when JSONAPI::Relationship::ToMany # Do nothing — already covered by policy scopes else raise "Unexpected relationship type: #{relationship.inspect}" end parent_record = parent_resource._model related_record = related_resource._model unless related_resource.nil? authorizer.show_relationship(source_record: parent_record, related_record: related_record) end def authorize_show_related_resource source_klass = params[:source_klass] source_id = params[:source_id] relationship_type = params[:relationship_type].to_sym source_resource = source_klass.find_by_key(source_id, context: context) related_resource = source_resource.public_send(relationship_type) source_record = source_resource._model related_record = related_resource._model unless related_resource.nil? authorizer.show_related_resource( source_record: source_record, related_record: related_record ) end def authorize_show_related_resources source_resource = params[:source_klass].find_by_key( params[:source_id], context: context ) source_record = source_resource._model authorizer.show_related_resources( source_record: source_record, related_record_class: @resource_klass._model_class ) end def authorize_replace_fields source_record = @resource_klass.find_by_key( params[:resource_id], context: context )._model authorizer.replace_fields( source_record: source_record, related_records_with_context: related_models_with_context ) end def authorize_create_resource source_class = resource_klass._model_class authorizer.create_resource( source_class: source_class, related_records_with_context: related_models_with_context ) end def authorize_remove_resource record = @resource_klass.find_by_key( operation_resource_id, context: context )._model authorizer.remove_resource(source_record: record) end def authorize_replace_to_one_relationship return authorize_remove_to_one_relationship if params[:key_value].nil? source_resource = @resource_klass.find_by_key( params[:resource_id], context: context ) source_record = source_resource._model relationship_type = params[:relationship_type].to_sym new_related_resource = @resource_klass ._relationship(relationship_type) .resource_klass .find_by_key( params[:key_value], context: context ) new_related_record = new_related_resource._model unless new_related_resource.nil? authorizer.replace_to_one_relationship( source_record: source_record, new_related_record: new_related_record, relationship_type: relationship_type ) end def authorize_create_to_many_relationships source_record = @resource_klass.find_by_key( params[:resource_id], context: context )._model relationship_type = params[:relationship_type].to_sym related_models = model_class_for_relationship(relationship_type).find(params[:data]) authorizer.create_to_many_relationship( source_record: source_record, new_related_records: related_models, relationship_type: relationship_type ) end def authorize_replace_to_many_relationships source_resource = @resource_klass.find_by_key( params[:resource_id], context: context ) source_record = source_resource._model relationship_type = params[:relationship_type].to_sym new_related_records = model_class_for_relationship(relationship_type).find(params[:data]) authorizer.replace_to_many_relationship( source_record: source_record, new_related_records: new_related_records, relationship_type: relationship_type ) end def authorize_remove_to_many_relationships source_resource = @resource_klass.find_by_key( params[:resource_id], context: context ) source_record = source_resource._model relationship_type = params[:relationship_type].to_sym related_resources = @resource_klass ._relationship(relationship_type) .resource_klass .find_by_keys( params[:associated_keys], context: context ) related_records = related_resources.map(&:_model) if related_records.size != params[:associated_keys].uniq.size raise JSONAPI::Exceptions::RecordNotFound, params[:associated_keys] end authorizer.remove_to_many_relationship( source_record: source_record, related_records: related_records, relationship_type: relationship_type ) end def authorize_remove_to_one_relationship source_record = @resource_klass.find_by_key( params[:resource_id], context: context )._model relationship_type = params[:relationship_type].to_sym authorizer.remove_to_one_relationship( source_record: source_record, relationship_type: relationship_type ) end def authorize_replace_polymorphic_to_one_relationship return authorize_remove_to_one_relationship if params[:key_value].nil? source_resource = @resource_klass.find_by_key( params[:resource_id], context: context ) source_record = source_resource._model # Fetch the name of the new class based on the incoming polymorphic # "type" value. This will fail if there is no associated resource for the # incoming "type" value so this shouldn't leak constants related_record_class_name = source_resource .send(:_model_class_name, params[:key_type]) # Fetch the underlying Resource class for the new record to-be-associated related_resource_klass = @resource_klass.resource_for(related_record_class_name) new_related_resource = related_resource_klass .find_by_key( params[:key_value], context: context ) new_related_record = new_related_resource._model unless new_related_resource.nil? relationship_type = params[:relationship_type].to_sym authorizer.replace_to_one_relationship( source_record: source_record, new_related_record: new_related_record, relationship_type: relationship_type ) end private def authorizer @authorizer ||= ::JSONAPI::Authorization.configuration.authorizer.new(context: context) end # TODO: Communicate with upstream to fix this nasty hack def operation_resource_id case operation_type when :show params[:id] when :show_related_resources params[:source_id] else params[:resource_id] end end def resource_class_for_relationship(assoc_name) @resource_klass._relationship(assoc_name).resource_klass end def model_class_for_relationship(assoc_name) resource_class_for_relationship(assoc_name)._model_class end def related_models_with_context data = params[:data] return { relationship: nil, relation_name: nil, records: nil } if data.nil? %i[to_one to_many].flat_map do |rel_type| data[rel_type].flat_map do |assoc_name, assoc_value| related_models = case assoc_value when nil nil when Hash # polymorphic relationship resource_class = @resource_klass.resource_for(assoc_value[:type].to_s) resource_class.find_by_key(assoc_value[:id], context: context)._model when Array resource_class = resource_class_for_relationship(assoc_name) resources = resource_class.find_by_keys(assoc_value, context: context) resources.map(&:_model).tap do |scoped_records| related_ids = Array.wrap(assoc_value).uniq if scoped_records.count != related_ids.count raise JSONAPI::Exceptions::RecordNotFound, related_ids end end else resource_class = resource_class_for_relationship(assoc_name) resource_class.find_by_key(assoc_value, context: context)._model end { relation_type: rel_type, relation_name: assoc_name, records: related_models } end end end def authorize_model_includes(source_record) return unless params[:include_directives] params[:include_directives].model_includes.each do |include_item| authorize_include_item(@resource_klass, source_record, include_item) end end def authorize_include_item(resource_klass, source_record, include_item) case include_item when Hash # e.g. {articles: [:comments, :author]} when ?include=articles.comments,articles.author include_item.each do |rel_name, deep| authorize_include_item(resource_klass, source_record, rel_name) relationship = resource_klass._relationship(rel_name) next_resource_klass = relationship.resource_klass Array.wrap( source_record.public_send( relationship.relation_name(context: context) ) ).each do |next_source_record| deep.each do |next_include_item| authorize_include_item( next_resource_klass, next_source_record, next_include_item ) end end end when Symbol relationship = resource_klass._relationship(include_item) case relationship when JSONAPI::Relationship::ToOne related_record = source_record.public_send( relationship.relation_name(context: context) ) return if related_record.nil? authorizer.include_has_one_resource( source_record: source_record, related_record: related_record ) when JSONAPI::Relationship::ToMany authorizer.include_has_many_resource( source_record: source_record, record_class: relationship.resource_klass._model_class ) else raise "Unexpected relationship type: #{relationship.inspect}" end else raise "Unknown include directive: #{include_item}" end end end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/lib/jsonapi/authorization/pundit_scoped_resource.rb
lib/jsonapi/authorization/pundit_scoped_resource.rb
# frozen_string_literal: true require 'pundit' module JSONAPI module Authorization module PunditScopedResource extend ActiveSupport::Concern module ClassMethods def records(options = {}) user_context = JSONAPI::Authorization.configuration.user_context(options[:context]) ::Pundit.policy_scope!(user_context, _model_class) end end def records_for(association_name) record_or_records = @model.public_send(association_name) relationship = fetch_relationship(association_name) case relationship when JSONAPI::Relationship::ToOne record_or_records when JSONAPI::Relationship::ToMany user_context = JSONAPI::Authorization.configuration.user_context(context) ::Pundit.policy_scope!(user_context, record_or_records) else raise "Unknown relationship type #{relationship.inspect}" end end private def fetch_relationship(association_name) relationships = self.class._relationships.select do |_k, v| v.relation_name(context: context) == association_name end if relationships.empty? nil else relationships.values.first end end end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
venuu/jsonapi-authorization
https://github.com/venuu/jsonapi-authorization/blob/3184da84e3d83ae2bef4e472232680efa6e5b52c/lib/jsonapi/authorization/configuration.rb
lib/jsonapi/authorization/configuration.rb
# frozen_string_literal: true require 'jsonapi/authorization/default_pundit_authorizer' module JSONAPI module Authorization class Configuration attr_accessor :authorizer, :pundit_user def initialize self.authorizer = ::JSONAPI::Authorization::DefaultPunditAuthorizer self.pundit_user = :user end def user_context(context) if pundit_user.is_a?(Symbol) context[pundit_user] else pundit_user.call(context) end end end class << self attr_accessor :configuration end @configuration ||= Configuration.new def self.configure yield(@configuration) end end end
ruby
MIT
3184da84e3d83ae2bef4e472232680efa6e5b52c
2026-01-04T17:49:48.253126Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/test/test_summarize_average.rb
test/test_summarize_average.rb
require_relative "./test_helper" require_relative "./test_data" class TestSummarize < Minitest::Test include AssertNoopEqual def test_simple_average_age compare_noop do |noop| Person.summarize(noop: noop) { |p| p.average(:age).round(10) } end end def test_grouped_average_age compare_noop do |noop| Person.summarize(noop: noop) do |p| p.group(:number_of_cats).average(:age).transform_values { |v| v.round(10) } end end assert_equal( Person.group(:number_of_cats).average(:age).transform_values { |v| v.round(10) }, Person.group(:number_of_cats).summarize { |p| p.average(:age).round(10) } ) end def test_average_with_other_group compare_noop do |noop| Person.summarize(noop: noop) do |p| [ p.average(:age).round(10), p.where(number_of_cats: 1..).group(:number_of_cats).count ] end end end def test_average_with_nested_group_and_filter demo_sql_fragment = Arel.sql("case age >= 50 when 1 then 'senior' else 'junior' end") summary = Person.group(:favorite_color_id).summarize do |p| { how_many: p.count, avg_adult_age: p.where(age: 18..).average(:age).round(10), demographic_cats: p.group(demo_sql_fragment).average(:number_of_cats).transform_values { |v| v.round(10) } } end assert_equal( Person.group(:favorite_color_id).count, summary.transform_values { |v| v[:how_many] }, "basic favorite color count did not match" ) assert_equal( Person.group(:favorite_color_id).where(age: 18..).average(:age).transform_values { |v| v.round(10) }, summary.transform_values { |v| v[:avg_adult_age] }, "grouped & filtered avg age did not match" ) assert_equal( Person.group(:favorite_color_id, demo_sql_fragment).average(:number_of_cats).transform_values { |v| v.round(10) }, summary.flat_map do |key_a, s| s[:demographic_cats].map do |key_b, avg| [[key_a, key_b], avg] end end.to_h, "double-grouped and filtered average didn't match" ) end end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/test/test_data.rb
test/test_data.rb
require_relative "./test_helper" # Choose a connection. In the future, we'll come up with some way to automate it. ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: ":memory:" ) # ActiveRecord::Base.establish_connection( # adapter: "postgresql", # encoding: "unicode", # database: "summarize_test" # ) stdout_logger = Logger.new($stdout) # ActiveRecord::Base.logger = stdout_logger # Usually don't want to see all the inserts, but if you're changing them you might SILLY_WORDS = %w[Abibliophobia Absquatulate Batrachomyomachy Bibble Billingsgate Bloviate Borborygm Boustrophedon Bowyang Brouhaha Bumbershoot Bumfuzzle Canoodle Cantankerous Cattywampus Cockamamie Codswallop Collop Collywobbles Comeuppance Crapulence Donnybrook Doozy Erinaceous Fard Fatuous Flibbertigibbet Fuddy-duddy Gardyloo Gobbledygook Godwottery Gonzo Goombah Gubbins Hobbledehoy Hocus-pocus Impignorate Lickety-split Lollygag Malarkey Mollycoddle Mugwump Namby-pamby Nincompoop Nudiustertian Ornery Pandiculation Pauciloquent Pettifogger Quire Ratoon Rigmarole Shenanigan Sialoquent Skedaddle Smellfungus Snickersnee Snollygoster Snool TroglodyteWabbit Widdershins Xertz Yarborough Zoanthropy] COLORS = %w[Red Orange Yellow Green Blue Indigo Violet] ActiveRecord::Schema.define do # In Postgres, must drop tables explicitly in reverse order so that foreign # keys don't get in the way. In SQLite :memory: db, these lines do nothing. drop_table :clubs_people, if_exists: true drop_table :clubs, if_exists: true drop_table :people, if_exists: true drop_table :colors, if_exists: true create_table :colors, force: true do |t| t.string :name end create_table :people, force: true do |t| t.string :name t.float :age t.integer :number_of_cats t.belongs_to :favorite_color, foreign_key: {to_table: :colors} end create_table :clubs, force: true do |t| t.string :name end create_join_table :clubs, :people end class Color < ActiveRecord::Base has_many :fans, class_name: "Person", foreign_key: :favorite_color_id, inverse_of: :favorite_color end class Person < ActiveRecord::Base belongs_to :favorite_color, class_name: "Color" has_and_belongs_to_many :clubs scope :with_long_name, ->(gt: 20) { where("length(#{table_name}.name) > ?", gt) } def self.generate_random! create!( name: SILLY_WORDS.sample(2).join(" "), age: (rand(0...9) == 0) ? nil : rand(6.0...100.0), number_of_cats: (rand(0...10) == 0) ? nil : rand(0..3), favorite_color_id: rand(1..COLORS.length) ) end end class Club < ActiveRecord::Base has_and_belongs_to_many :members, class_name: "Person" SILLY_WORDS = %w[Abibliophobia Absquatulate Batrachomyomachy Bibble Billingsgate Bloviate Borborygm Boustrophedon Bowyang Brouhaha Bumbershoot Bumfuzzle Canoodle Cantankerous Cattywampus Cockamamie Codswallop Collop Collywobbles Comeuppance Crapulence Donnybrook Doozy Erinaceous Fard Fatuous Flibbertigibbet Fuddy-duddy Gardyloo Gobbledygook Godwottery Gonzo Goombah Gubbins Hobbledehoy Hocus-pocus Impignorate Lickety-split Lollygag Malarkey Mollycoddle Mugwump Namby-pamby Nincompoop Nudiustertian Ornery Pandiculation Pauciloquent Pettifogger Quire Ratoon Rigmarole Shenanigan Sialoquent Skedaddle Smellfungus Snickersnee Snollygoster Snool TroglodyteWabbit Widdershins Xertz Yarborough Zoanthropy] def self.generate_random!(members) create!(name: SILLY_WORDS.sample(2).join(" "), members: members) end end Color.transaction do COLORS.each_with_index { |name, i| Color.create(name: name, id: i + 1) } end Person.transaction do 500.times { Person.generate_random! } end Club.transaction do people = Person.all 30.times { Club.generate_random!(people.sample(rand(3..60))) } end # Often helpful to see the queries the tests run ActiveRecord::Base.logger = stdout_logger
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/test/test_chainable_result.rb
test/test_chainable_result.rb
require_relative "./test_helper" require_relative "./test_data" class TestChainableResult < Minitest::Test def test_with_invocations counts, factor, addends = toy_values.map { |v| ChainableResult.wrap(v) } # A single value assert_equal( {123 => :foo, 200 => :bar}, ChainableResult::WITH_RESOLVED[counts] { |h| h.to_h { |k, v| [v, k] } }.value ) # Two values with a block that receives two arguments assert_equal( {foo: 369, bar: 600}, ChainableResult::WITH_RESOLVED[counts, factor] { |h, f| h.transform_values { |v| v * f } }.value ) # Two values with a block that receives one argument (as an array) assert_equal( 163, ChainableResult::WITH_RESOLVED[factor, addends] { |vs| vs.flatten.sum }.value ) # Three values with a block that receives three arguments assert_equal( {foo: 469, bar: 660}, ChainableResult::WITH_RESOLVED[counts, factor, addends] { |h, f, a| h.transform_values.each_with_index { |v, i| v * f + a[i] } }.value ) # Three values with a block that receives two arguments (there's probably no good reason to do this) assert_equal( {foo: 369, bar: 600}, ChainableResult::WITH_RESOLVED[counts, factor, addends] { |h, f| h.transform_values { |v| v * f } }.value ) # Repeated argument and symbol proc assert_equal( 9, ChainableResult::WITH_RESOLVED[factor, factor, factor, &:sum].value ) end def test_sync_with_invocations counts, factor, addends = toy_values # A single value assert_equal( {123 => :foo, 200 => :bar}, ChainableResult::SYNC_WITH_RESOLVED[counts] { |h| h.to_h { |k, v| [v, k] } } ) # Two values with a block that receives two arguments assert_equal( {foo: 369, bar: 600}, ChainableResult::SYNC_WITH_RESOLVED[counts, factor] { |h, f| h.transform_values { |v| v * f } } ) # Two values with a block that receives one argument (as an array) assert_equal( 163, ChainableResult::SYNC_WITH_RESOLVED[factor, addends] { |vs| vs.flatten.sum } ) # Three values with a block that receives three arguments assert_equal( {foo: 469, bar: 660}, ChainableResult::SYNC_WITH_RESOLVED[counts, factor, addends] { |h, f, a| h.transform_values.each_with_index { |v, i| v * f + a[i] } } ) # Three values with a block that receives two arguments (there's probably no good reason to do this) assert_equal( {foo: 369, bar: 600}, ChainableResult::SYNC_WITH_RESOLVED[counts, factor, addends] { |h, f| h.transform_values { |v| v * f } } ) # Repeated argument and symbol proc assert_equal( 9, ChainableResult::SYNC_WITH_RESOLVED[factor, factor, factor, &:sum] ) end private def toy_values [{foo: 123, bar: 200}, 3, [100, 60]] end end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true $LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "active_record" require "activerecord/summarize" require "minitest/autorun" module AssertNoopEqual def compare_noop(message = "was not equal with noop: true and noop: false") noop_result = yield(true) result = yield(false) assert_equal noop_result, result result end end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/test/test_summarize_minimum_maximum.rb
test/test_summarize_minimum_maximum.rb
require_relative "./test_helper" require_relative "./test_data" class TestSummarize < Minitest::Test include AssertNoopEqual def test_simple_minmax_age compare_noop do |noop| Person.summarize(noop: noop) do |p| [p.minimum(:age), p.maximum(:age)] end end end def test_grouped_minmax_age compare_noop do |noop| Person.summarize(noop: noop) do |p| [p.group(:number_of_cats).minimum(:age), p.group(:number_of_cats).minimum(:age)] end end assert_equal( Person.group(:number_of_cats).minimum(:age), Person.group(:number_of_cats).summarize { |p| p.minimum(:age) } ) assert_equal( Person.group(:number_of_cats).maximum(:age), Person.group(:number_of_cats).summarize { |p| p.maximum(:age) } ) end def test_minmax_with_other_group compare_noop do |noop| Person.summarize(noop: noop) do |p| [ p.minimum(:age), p.maximum(:age), p.where(number_of_cats: 1..).group(:number_of_cats).count ] end end end def test_minmax_with_nested_group_and_filter demo_sql_fragment = Arel.sql("case age >= 50 when 1 then 'senior' else 'junior' end") summary = Person.group(:favorite_color_id).summarize do |p| { how_many: p.count, min_adult_age: p.where(age: 18..).minimum(:age), max_adult_age: p.where(age: 18..).maximum(:age), min_demographic_cats: p.group(demo_sql_fragment).minimum(:number_of_cats), max_demographic_cats: p.group(demo_sql_fragment).maximum(:number_of_cats) } end assert_equal( Person.group(:favorite_color_id).count, summary.transform_values { |v| v[:how_many] }, "basic favorite color count did not match" ) assert_equal( Person.group(:favorite_color_id).where(age: 18..).minimum(:age), summary.transform_values { |v| v[:min_adult_age] }, "grouped & filtered minimum age did not match" ) assert_equal( Person.group(:favorite_color_id).where(age: 18..).maximum(:age), summary.transform_values { |v| v[:max_adult_age] }, "grouped & filtered maximum age did not match" ) assert_equal( Person.group(:favorite_color_id, demo_sql_fragment).minimum(:number_of_cats), summary.flat_map do |key_a, s| s[:min_demographic_cats].map do |key_b, min| [[key_a, key_b], min] end end.to_h, "double-grouped and filtered minimum didn't match" ) assert_equal( Person.group(:favorite_color_id, demo_sql_fragment).maximum(:number_of_cats), summary.flat_map do |key_a, s| s[:max_demographic_cats].map do |key_b, max| [[key_a, key_b], max] end end.to_h, "double-grouped and filtered maximum didn't match" ) end end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/test/test_summarize.rb
test/test_summarize.rb
require_relative "./test_helper" require_relative "./test_data" class TestSummarize < Minitest::Test include AssertNoopEqual def test_that_it_has_a_version_number refute_nil ::ActiveRecord::Summarize::VERSION end def test_data_sanity assert_equal 500, Person.count # 1 in ~2.679 E 300 chance this isn't true assert_includes 2..4, Person.distinct.count(:number_of_cats) end def test_single_counts_are_accurate assert_equal Person.count, Person.summarize { |p| p.count } filtered = Person.where(number_of_cats: 1..) assert_equal filtered.count, filtered.summarize { |p| p.count } end def test_simple_grouped_count_is_accurate grouped = Person.group(:number_of_cats) assert_equal grouped.count, grouped.summarize { |p| p.count } end def test_summarizing cat_owners = Person.where(number_of_cats: 1..) long_name_where = "length(name) > 20" @exp_count = cat_owners.count @exp_where_count = cat_owners.where(long_name_where).count @exp_scope_count = cat_owners.with_long_name.count compare_noop do |noop| cat_owners.summarize(noop: noop) do |p| @count = p.count @where_count = p.where(long_name_where).count @scope_count = p.with_long_name.count [@count, @where_count, @scope_count] end end assert_equal @exp_count, @count assert_equal @exp_where_count, @where_count assert_equal @exp_scope_count, @scope_count end def test_sum_of_float_and_int # Starting with Rails 7.0.5, continuing through (at least) 7.0.7, in PostgreSQL only, # plucking the same aggregate function (e.g., sum) more than once without an alias # results in all such columns getting cast to the type of the last such column. people = Person.where.not(age: nil) a = people.summarize(noop: true) do |p| [p.sum(:age), p.sum(:number_of_cats)] end b = people.summarize(noop: false) do |p| [p.sum(:age), p.sum(:number_of_cats)] end assert_equal(a, b) end def test_prevents_distinct assert_raises(ActiveRecord::Summarize::Unsummarizable) do # This trivial case we actually could get right, but once we end up with additional group_values, distinct is likely to be wrong. Person.summarize { |p| p.distinct.count :number_of_cats } end assert_raises(ActiveRecord::Summarize::Unsummarizable) do Person.summarize { |p| p.count("distinct number_of_cats") } end end def test_grouped_with_proc avg_name_length_by_cats = Person.group(:number_of_cats).summarize do |p, with| with[p.sum("length(name)"), p.count] do |sum, count| sum.to_f / count end end exp = Person.group(:number_of_cats).sum("length(name)").merge( Person.group(:number_of_cats).count ) do |_key, sum, count| sum.to_f / count end assert_equal(exp, avg_name_length_by_cats) end def test_grouped_withless avg_name_length_by_cats = Person.group(:number_of_cats).summarize do |p| p.sum("length(name)").to_f / p.count end exp = Person.group(:number_of_cats).sum("length(name)").merge( Person.group(:number_of_cats).count ) do |_key, sum, count| sum.to_f / count end assert_equal(exp, avg_name_length_by_cats) end def test_most_popular_cat_number most_popular_cat_number = Person.joins(:favorite_color).group(:favorite_color).summarize do |p| p.group(:number_of_cats).count.max_by { |(k, v)| [v, k] } end exp = Color.all.to_h do |color| [color, color.fans.group(:number_of_cats).count.max_by { |(k, v)| [v, k] }] end assert_equal(exp, most_popular_cat_number) end def test_inside_grouping_with_proc avg_name_length_by_cats = compare_noop do |noop| Person.summarize(noop: noop) do |p, with| grouped = p.group(:number_of_cats) with[grouped.sum("length(name)"), grouped.count] do |sums, counts| sums.merge(counts) do |_key, sum, count| sum.to_f / count end end end end exp = Person.group(:number_of_cats).sum("length(name)").merge( Person.group(:number_of_cats).count ) do |_key, sum, count| sum.to_f / count end assert_equal(exp, avg_name_length_by_cats) end def test_correct_empty_result_shapes # where(name: "J"..."L") is empty because no words in SILLY_WORDS start with J or K (many, empty1, empty2, zero) = compare_noop do |noop| Person.summarize(noop: noop) do |p| [ p.group(:number_of_cats).count, p.where(name: "J"..."L").group(:number_of_cats).count, p.where(name: "J"..."L").group(:number_of_cats, :age).count, p.where(name: "J"..."L").count ] end end assert_equal false, many.empty? assert_equal true, empty1.is_a?(Hash) && empty1.empty? assert_equal true, empty2.is_a?(Hash) && empty2.empty? assert_equal true, zero.zero? end def test_null_sums_safely_reported_as_zero # SQL SUM(NULL) returns NULL, but in ActiveRecord .sum always returns a number # TODO: There's a small inconsistency with .sum of a Float or Decimal column when the calculation result is null: # - ActiveRecord.sum returns 0.0 # - .sum inside a summarize block returns integer 0 exp_single = Person.where(age: nil).sum(:age) # 0.0 exp_group = Person.group(:number_of_cats).where(age: nil).sum(:age) # {0=>0.0, 1=>0.0, 2=>0.0, 3=>0.0} exp_group2 = Person.group(:number_of_cats, Arel.sql("number_of_cats % 2")).where(age: nil).sum(:age) # {[0, 0]=>0.0, [1, 1]=>0.0, [2, 0]=>0.0, [3, 1]=>0.0} assert_equal exp_single, Person.summarize { |p| p.where(age: nil).sum(:age) } assert_equal exp_group, Person.group(:number_of_cats).summarize { |p| p.where(age: nil).sum(:age) } assert_equal exp_group2, Person.group(:number_of_cats, Arel.sql("number_of_cats % 2")).summarize { |p| p.where(age: nil).sum(:age) } end def test_habtm_join_trivial simple_count = Club.joins(:members).group(:id, :name).count summarize_count = Club.joins(:members).group(:id, :name).summarize do |clubs| clubs.count end assert_equal simple_count, summarize_count end def test_habtm_join_summary members = Club.joins(:members).group(:id, :name).count long_names = Club.joins(:members).group(:id, :name).merge(Person.with_long_name).count cat_owners = Club.all.each_with_object({}) do |club, obj| obj[[club.id, club.name]] = club.members.group(:number_of_cats).count end manual = members.to_h do |k, members| summary = { members: members, long_names: long_names[k] || 0, cat_owners: cat_owners[k] } [k, summary] end club_summary = Club.joins(:members).group(:id, :name).summarize do |clubs| { members: clubs.count, long_names: clubs.merge(Person.with_long_name).count, cat_owners: clubs.group(:number_of_cats).count } end assert_equal(manual, club_summary) end def test_belongs_to_model_group_by # Keys are Color models instead of (e.g.) colors.id scalars simple_count = Person.joins(:favorite_color).group(:favorite_color).count summarize_count = Person.joins(:favorite_color).group(:favorite_color).summarize do |people| people.count end assert_equal simple_count, summarize_count end def test_inside_grouping_withless avg_name_length_by_cats = Person.summarize do |p| grouped = p.group(:number_of_cats) sums = grouped.sum("length(name)") counts = grouped.count sums.merge(counts) do |_key, sum, count| sum.to_f / count end end exp = Person.group(:number_of_cats).sum("length(name)").merge( Person.group(:number_of_cats).count ) do |_key, sum, count| sum.to_f / count end assert_equal(exp, avg_name_length_by_cats) end end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false
midnightmonster/activerecord-summarize
https://github.com/midnightmonster/activerecord-summarize/blob/7371f06ce47b2bc6966a5b8297aa95aaee2c59de/lib/chainable_result.rb
lib/chainable_result.rb
class ChainableResult def initialize(source, method = nil, args = [], opts = {}, &block) @source = source @method = method || (block ? :then : :itself) @args = args @opts = opts @block = block @cached = false end def value if use_cache? return @value if @cached @cached = true @value = resolve_source.send( @method, *@args.map(&RESOLVE_ITEM), **@opts.transform_values(&RESOLVE_ITEM), &@block ) else resolve_source.send( @method, *@args.map(&RESOLVE_ITEM), **@opts.transform_values(&RESOLVE_ITEM), &@block ) end end def to_json(**opts) ChainableResult::Future.new(self, :to_json, [], opts) end def then(&block) ChainableResult::Future.new(self, :then, &block) end def yield_self(&block) ChainableResult::Future.new(self, :yield_self, &block) end def tap(&block) ChainableResult::Future.new(self, :tap, &block) end def method_missing(method, *args, **opts, &block) ChainableResult::Future.new(self, method, args, opts, &block) end def respond_to_missing?(method_name, include_private = false) true end class Future < self def resolve_source @source.value end end class Array < self def resolve_source @source.map(&RESOLVE_ITEM) end end class Hash < self def resolve_source @source.transform_values(&RESOLVE_ITEM) end end class Other < self def resolve_source @source end end def self.wrap(v, method = nil, *args, **opts, &block) method ||= block ? :then : :itself klass = case v when ChainableResult then ChainableResult::Future when ::Array then ChainableResult::Array when ::Hash then ChainableResult::Hash else ChainableResult::Other end klass.new(v, method, args, opts, &block) end def self.with(*results, &block) ChainableResult.wrap((results.size == 1) ? results.first : results, :then, &block) end def self.sync_with(*results, &block) # Non-time-traveling, synchronous version of `with` for testing ((results.size == 1) ? results.first : results).then(&block) end # Shorter names are deprecated WITH_RESOLVED = WITH = method(:with) SYNC_WITH_RESOLVED = SYNC_WITH = method(:sync_with) def self.resolve_item(item) case item when ChainableResult then item.value when ::Array then ChainableResult::Array.new(item).value when ::Hash then ChainableResult::Hash.new(item).value else item end end RESOLVE_ITEM = method(:resolve_item) CACHE_MODE_KEY = :"ChainableResult::USE_CACHE" def self.with_cache(mode = true) prev = Thread.current[CACHE_MODE_KEY] Thread.current[CACHE_MODE_KEY] = mode result = yield Thread.current[CACHE_MODE_KEY] = prev result end private def use_cache? !!Thread.current[CACHE_MODE_KEY] end end
ruby
MIT
7371f06ce47b2bc6966a5b8297aa95aaee2c59de
2026-01-04T17:49:56.082596Z
false