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 | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/gemspec/attribute_assignment.rb | lib/rubocop/cop/gemspec/attribute_assignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Gemspec
# Use consistent style for Gemspec attributes assignment.
#
# @example
#
# # bad
# # This example uses two styles for assignment of metadata attribute.
# Gem::Specification.new do |spec|
# spec.metadata = { 'key' => 'value' }
# spec.metadata['another-key'] = 'another-value'
# end
#
# # good
# Gem::Specification.new do |spec|
# spec.metadata['key'] = 'value'
# spec.metadata['another-key'] = 'another-value'
# end
#
# # good
# Gem::Specification.new do |spec|
# spec.metadata = { 'key' => 'value', 'another-key' => 'another-value' }
# end
#
# # bad
# # This example uses two styles for assignment of authors attribute.
# Gem::Specification.new do |spec|
# spec.authors = %w[author-0 author-1]
# spec.authors[2] = 'author-2'
# end
#
# # good
# Gem::Specification.new do |spec|
# spec.authors = %w[author-0 author-1 author-2]
# end
#
# # good
# Gem::Specification.new do |spec|
# spec.authors[0] = 'author-0'
# spec.authors[1] = 'author-1'
# spec.authors[2] = 'author-2'
# end
#
# # good
# # This example uses consistent assignment per attribute,
# # even though two different styles are used overall.
# Gem::Specification.new do |spec|
# spec.metadata = { 'key' => 'value' }
# spec.authors[0] = 'author-0'
# spec.authors[1] = 'author-1'
# spec.authors[2] = 'author-2'
# end
#
class AttributeAssignment < Base
include GemspecHelp
MSG = 'Use consistent style for Gemspec attributes assignment.'
def on_new_investigation
return if processed_source.blank?
assignments = source_assignments(processed_source.ast)
indexed_assignments = source_indexed_assignments(processed_source.ast)
assignments.keys.intersection(indexed_assignments.keys).each do |attribute|
indexed_assignments[attribute].each do |node|
add_offense(node)
end
end
end
private
def source_assignments(ast)
assignment_method_declarations(ast)
.select(&:assignment_method?)
.group_by(&:method_name)
.transform_keys { |method_name| method_name.to_s.delete_suffix('=').to_sym }
end
def source_indexed_assignments(ast)
indexed_assignment_method_declarations(ast)
.group_by { |node| node.children.first.method_name }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/gemspec/duplicated_assignment.rb | lib/rubocop/cop/gemspec/duplicated_assignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Gemspec
# An attribute assignment method calls should be listed only once
# in a gemspec.
#
# Assigning to an attribute with the same name using `spec.foo =` or
# `spec.attribute#[]=` will be an unintended usage. On the other hand,
# duplication of methods such # as `spec.requirements`,
# `spec.add_runtime_dependency`, and others are permitted because it is
# the intended use of appending values.
#
# @example
# # bad
# Gem::Specification.new do |spec|
# spec.name = 'rubocop'
# spec.name = 'rubocop2'
# end
#
# # good
# Gem::Specification.new do |spec|
# spec.name = 'rubocop'
# end
#
# # good
# Gem::Specification.new do |spec|
# spec.requirements << 'libmagick, v6.0'
# spec.requirements << 'A good graphics card'
# end
#
# # good
# Gem::Specification.new do |spec|
# spec.add_dependency('parallel', '~> 1.10')
# spec.add_dependency('parser', '>= 2.3.3.1', '< 3.0')
# end
#
# # bad
# Gem::Specification.new do |spec|
# spec.metadata["key"] = "value"
# spec.metadata["key"] = "value"
# end
#
# # good
# Gem::Specification.new do |spec|
# spec.metadata["key"] = "value"
# end
#
class DuplicatedAssignment < Base
include RangeHelp
include GemspecHelp
MSG = '`%<assignment>s` method calls already given on line ' \
'%<line_of_first_occurrence>d of the gemspec.'
def on_new_investigation
return if processed_source.blank?
process_assignment_method_nodes
process_indexed_assignment_method_nodes
end
private
def process_assignment_method_nodes
duplicated_assignment_method_nodes.each do |nodes|
nodes[1..].each do |node|
register_offense(node, node.method_name, nodes.first.first_line)
end
end
end
def process_indexed_assignment_method_nodes
duplicated_indexed_assignment_method_nodes.each do |nodes|
nodes[1..].each do |node|
assignment = "#{node.children.first.method_name}[#{node.first_argument.source}]="
register_offense(node, assignment, nodes.first.first_line)
end
end
end
def duplicated_assignment_method_nodes
assignment_method_declarations(processed_source.ast)
.select(&:assignment_method?)
.group_by(&:method_name)
.values
.select { |nodes| nodes.size > 1 }
end
def duplicated_indexed_assignment_method_nodes
indexed_assignment_method_declarations(processed_source.ast)
.group_by { |node| [node.children.first.method_name, node.first_argument] }
.values
.select { |nodes| nodes.size > 1 }
end
def register_offense(node, assignment, line_of_first_occurrence)
line_range = node.loc.column...node.loc.last_column
offense_location = source_range(processed_source.buffer, node.first_line, line_range)
message = format(
MSG,
assignment: assignment,
line_of_first_occurrence: line_of_first_occurrence
)
add_offense(offense_location, message: message)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/migration/department_name.rb | lib/rubocop/cop/migration/department_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Migration
# Check that cop names in rubocop:disable comments are given with
# department name.
class DepartmentName < Base
include RangeHelp
extend AutoCorrector
MSG = 'Department name is missing.'
DISABLE_COMMENT_FORMAT = /\A(# *rubocop *: *((dis|en)able|todo) +)(.*)/.freeze
# The token that makes up a disable comment.
# The allowed specification for comments after `# rubocop: disable` is
# `DepartmentName/CopName` or` all`.
DISABLING_COPS_CONTENT_TOKEN = %r{[A-Za-z]+/[A-Za-z]+|all}.freeze
def on_new_investigation
processed_source.comments.each do |comment|
next if comment.text !~ DISABLE_COMMENT_FORMAT
offset = Regexp.last_match(1).length
Regexp.last_match(4).scan(/[^,]+|\W+/) do |name|
trimmed_name = name.strip
unless valid_content_token?(trimmed_name)
check_cop_name(trimmed_name, comment, offset)
end
break if contain_unexpected_character_for_department_name?(name)
offset += name.length
end
end
end
private
def disable_comment_offset
Regexp.last_match(1).length
end
def check_cop_name(name, comment, offset)
start = comment.source_range.begin_pos + offset
range = range_between(start, start + name.length)
add_offense(range) do |corrector|
cop_name = range.source
qualified_cop_name = Registry.global.qualified_cop_name(cop_name, nil, warn: false)
unless qualified_cop_name.include?('/')
qualified_cop_name = qualified_legacy_cop_name(cop_name)
end
corrector.replace(range, qualified_cop_name)
end
end
def valid_content_token?(content_token)
/\W+/.match?(content_token) ||
DISABLING_COPS_CONTENT_TOKEN.match?(content_token) ||
Registry.global.department?(content_token)
end
def contain_unexpected_character_for_department_name?(name)
name.match?(%r{[^A-Za-z/, ]})
end
def qualified_legacy_cop_name(cop_name)
legacy_cop_names = RuboCop::ConfigObsoletion.legacy_cop_names
legacy_cop_names.detect { |legacy_cop_name| legacy_cop_name.split('/')[1] == cop_name }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/legacy/corrector.rb | lib/rubocop/cop/legacy/corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Legacy
# Legacy Corrector for v0 API support.
# See https://docs.rubocop.org/rubocop/v1_upgrade_notes.html
class Corrector < RuboCop::Cop::Corrector
# Support legacy second argument
def initialize(source, corr = [])
super(source)
if corr.is_a?(CorrectionsProxy)
merge!(corr.send(:corrector))
else
unless corr.empty?
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`Corrector.new` with corrections is deprecated.
See https://docs.rubocop.org/rubocop/v1_upgrade_notes.html
WARNING
end
corr.each { |c| corrections << c }
end
end
def corrections
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`Corrector#corrections` is deprecated. Open an issue if you have a valid usecase.
See https://docs.rubocop.org/rubocop/v1_upgrade_notes.html
WARNING
CorrectionsProxy.new(self)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/legacy/corrections_proxy.rb | lib/rubocop/cop/legacy/corrections_proxy.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Legacy
# Legacy support for Corrector#corrections
# See https://docs.rubocop.org/rubocop/v1_upgrade_notes.html
class CorrectionsProxy
def initialize(corrector)
@corrector = corrector
end
def <<(callable)
suppress_clobbering { @corrector.transaction { callable.call(@corrector) } }
end
def empty?
@corrector.empty?
end
def concat(corrections)
if corrections.is_a?(CorrectionsProxy)
suppress_clobbering { corrector.merge!(corrections.corrector) }
else
corrections.each { |correction| self << correction }
end
end
protected
attr_reader :corrector
private
def suppress_clobbering
yield
rescue ::Parser::ClobberingError
# ignore Clobbering errors
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/security/yaml_load.rb | lib/rubocop/cop/security/yaml_load.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Security
# Checks for the use of YAML class methods which have
# potential security issues leading to remote code execution when
# loading from an untrusted source.
#
# NOTE: Ruby 3.1+ (Psych 4) uses `Psych.load` as `Psych.safe_load` by default.
#
# @safety
# The behavior of the code might change depending on what was
# in the YAML payload, since `YAML.safe_load` is more restrictive.
#
# @example
# # bad
# YAML.load("--- !ruby/object:Foo {}") # Psych 3 is unsafe by default
#
# # good
# YAML.safe_load("--- !ruby/object:Foo {}", [Foo]) # Ruby 2.5 (Psych 3)
# YAML.safe_load("--- !ruby/object:Foo {}", permitted_classes: [Foo]) # Ruby 3.0- (Psych 3)
# YAML.load("--- !ruby/object:Foo {}", permitted_classes: [Foo]) # Ruby 3.1+ (Psych 4)
# YAML.dump(foo)
#
class YAMLLoad < Base
extend AutoCorrector
extend TargetRubyVersion
MSG = 'Prefer using `YAML.safe_load` over `YAML.load`.'
RESTRICT_ON_SEND = %i[load].freeze
maximum_target_ruby_version 3.0
# @!method yaml_load(node)
def_node_matcher :yaml_load, <<~PATTERN
(send (const {nil? cbase} :YAML) :load ...)
PATTERN
def on_send(node)
yaml_load(node) do
add_offense(node.loc.selector) do |corrector|
corrector.replace(node.loc.selector, 'safe_load')
end
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/security/marshal_load.rb | lib/rubocop/cop/security/marshal_load.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Security
# Checks for the use of Marshal class methods which have
# potential security issues leading to remote code execution when
# loading from an untrusted source.
#
# @example
# # bad
# Marshal.load("{}")
# Marshal.restore("{}")
#
# # good
# Marshal.dump("{}")
#
# # okish - deep copy hack
# Marshal.load(Marshal.dump({}))
#
class MarshalLoad < Base
MSG = 'Avoid using `Marshal.%<method>s`.'
RESTRICT_ON_SEND = %i[load restore].freeze
# @!method marshal_load(node)
def_node_matcher :marshal_load, <<~PATTERN
(send (const {nil? cbase} :Marshal) ${:load :restore}
!(send (const {nil? cbase} :Marshal) :dump ...))
PATTERN
def on_send(node)
marshal_load(node) do |method|
add_offense(node.loc.selector, message: format(MSG, method: method))
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/security/io_methods.rb | lib/rubocop/cop/security/io_methods.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Security
# Checks for the first argument to `IO.read`, `IO.binread`, `IO.write`, `IO.binwrite`,
# `IO.foreach`, and `IO.readlines`.
#
# If argument starts with a pipe character (`'|'`) and the receiver is the `IO` class,
# a subprocess is created in the same way as `Kernel#open`, and its output is returned.
# `Kernel#open` may allow unintentional command injection, which is the reason these
# `IO` methods are a security risk.
# Consider to use `File.read` to disable the behavior of subprocess invocation.
#
# @safety
# This cop is unsafe because false positive will occur if the variable passed as
# the first argument is a command that is not a file path.
#
# @example
#
# # bad
# IO.read(path)
# IO.read('path')
#
# # good
# File.read(path)
# File.read('path')
# IO.read('| command') # Allow intentional command invocation.
#
class IoMethods < Base
extend AutoCorrector
MSG = '`File.%<method_name>s` is safer than `IO.%<method_name>s`.'
RESTRICT_ON_SEND = %i[read binread write binwrite foreach readlines].freeze
def on_send(node)
return unless (receiver = node.receiver) && receiver.source == 'IO'
argument = node.first_argument
return if argument.respond_to?(:value) && argument.value.strip.start_with?('|')
add_offense(node, message: format(MSG, method_name: node.method_name)) do |corrector|
corrector.replace(receiver, 'File')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/security/open.rb | lib/rubocop/cop/security/open.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Security
# Checks for the use of `Kernel#open` and `URI.open` with dynamic
# data.
#
# `Kernel#open` and `URI.open` enable not only file access but also process
# invocation by prefixing a pipe symbol (e.g., `open("| ls")`).
# So, it may lead to a serious security risk by using variable input to
# the argument of `Kernel#open` and `URI.open`. It would be better to use
# `File.open`, `IO.popen` or `URI.parse#open` explicitly.
#
# NOTE: `open` and `URI.open` with literal strings are not flagged by this
# cop.
#
# @safety
# This cop could register false positives if `open` is redefined
# in a class and then used without a receiver in that class.
#
# @example
# # bad
# open(something)
# open("| #{something}")
# open("| foo")
# URI.open(something)
#
# # good
# File.open(something)
# IO.popen(something)
# URI.parse(something).open
#
# # good (literal strings)
# open("foo.text")
# URI.open("http://example.com")
# URI.parse(url).open
class Open < Base
MSG = 'The use of `%<receiver>sopen` is a serious security risk.'
RESTRICT_ON_SEND = %i[open].freeze
# @!method open?(node)
def_node_matcher :open?, <<~PATTERN
(send ${nil? (const {nil? cbase} :URI)} :open $_ ...)
PATTERN
def on_send(node)
open?(node) do |receiver, code|
return if safe?(code)
message = format(MSG, receiver: receiver ? "#{receiver.source}." : 'Kernel#')
add_offense(node.loc.selector, message: message)
end
end
private
def safe?(node)
if simple_string?(node)
safe_argument?(node.str_content)
elsif composite_string?(node)
safe?(node.children.first)
else
false
end
end
def safe_argument?(argument)
!argument.empty? && !argument.start_with?('|')
end
def simple_string?(node)
node.str_type?
end
def composite_string?(node)
interpolated_string?(node) || concatenated_string?(node)
end
def interpolated_string?(node)
node.dstr_type?
end
def concatenated_string?(node)
node.send_type? && node.method?(:+) && node.receiver.str_type?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/security/compound_hash.rb | lib/rubocop/cop/security/compound_hash.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Security
# Checks for implementations of the `hash` method which combine
# values using custom logic instead of delegating to `Array#hash`.
#
# Manually combining hashes is error prone and hard to follow, especially
# when there are many values. Poor implementations may also introduce
# performance or security concerns if they are prone to collisions.
# Delegating to `Array#hash` is clearer and safer, although it might be slower
# depending on the use case.
#
# @safety
# This cop may be unsafe if the application logic depends on the hash
# value, however this is inadvisable anyway.
#
# @example
#
# # bad
# def hash
# @foo ^ @bar
# end
#
# # good
# def hash
# [@foo, @bar].hash
# end
class CompoundHash < Base
COMBINATOR_IN_HASH_MSG = 'Use `[...].hash` instead of combining hash values manually.'
MONUPLE_HASH_MSG =
'Delegate hash directly without wrapping in an array when only using a single value.'
REDUNDANT_HASH_MSG = 'Calling .hash on elements of a hashed array is redundant.'
RESTRICT_ON_SEND = %i[hash ^ + * |].freeze
# @!method hash_method_definition?(node)
def_node_matcher :hash_method_definition?, <<~PATTERN
{#static_hash_method_definition? | #dynamic_hash_method_definition?}
PATTERN
# @!method dynamic_hash_method_definition?(node)
def_node_matcher :dynamic_hash_method_definition?, <<~PATTERN
(block
(send _ {:define_method | :define_singleton_method}
(sym :hash))
(args)
_)
PATTERN
# @!method static_hash_method_definition?(node)
def_node_matcher :static_hash_method_definition?, <<~PATTERN
({def | defs _} :hash
(args)
_)
PATTERN
# @!method bad_hash_combinator?(node)
def_node_matcher :bad_hash_combinator?, <<~PATTERN
({send | op-asgn} _ {:^ | :+ | :* | :|} _)
PATTERN
# @!method monuple_hash?(node)
def_node_matcher :monuple_hash?, <<~PATTERN
(send (array _) :hash)
PATTERN
# @!method redundant_hash?(node)
def_node_matcher :redundant_hash?, <<~PATTERN
(
^^(send array ... :hash)
_ :hash
)
PATTERN
def contained_in_hash_method?(node, &block)
node.each_ancestor.any? do |ancestor|
hash_method_definition?(ancestor, &block)
end
end
def outer_bad_hash_combinator?(node)
bad_hash_combinator?(node) do
yield true if node.each_ancestor.none? { |ancestor| bad_hash_combinator?(ancestor) }
end
end
def on_send(node)
outer_bad_hash_combinator?(node) do
contained_in_hash_method?(node) do
add_offense(node, message: COMBINATOR_IN_HASH_MSG)
end
end
monuple_hash?(node) do
add_offense(node, message: MONUPLE_HASH_MSG)
end
redundant_hash?(node) do
add_offense(node, message: REDUNDANT_HASH_MSG)
end
end
alias on_csend on_send
alias on_op_asgn on_send
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/security/eval.rb | lib/rubocop/cop/security/eval.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Security
# Checks for the use of `Kernel#eval` and `Binding#eval`.
#
# @example
#
# # bad
#
# eval(something)
# binding.eval(something)
# Kernel.eval(something)
class Eval < Base
MSG = 'The use of `eval` is a serious security risk.'
RESTRICT_ON_SEND = %i[eval].freeze
# @!method eval?(node)
def_node_matcher :eval?, <<~PATTERN
(send {nil? (send nil? :binding) (const {cbase nil?} :Kernel)} :eval $!str ...)
PATTERN
def on_send(node)
eval?(node) do |code|
return if code.dstr_type? && code.recursive_literal?
add_offense(node.loc.selector)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/security/json_load.rb | lib/rubocop/cop/security/json_load.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Security
# Checks for the use of JSON class methods which have potential
# security issues.
#
# `JSON.load` and similar methods allow deserialization of arbitrary ruby objects:
#
# [source,ruby]
# ----
# require 'json/add/string'
# result = JSON.load('{ "json_class": "String", "raw": [72, 101, 108, 108, 111] }')
# pp result # => "Hello"
# ----
#
# Never use `JSON.load` for untrusted user input. Prefer `JSON.parse` unless you have
# a concrete use-case for `JSON.load`.
#
# NOTE: Starting with `json` gem version 2.8.0, triggering this behavior without explicitly
# passing the `create_additions` keyword argument emits a deprecation warning, with the
# goal of being secure by default in the next major version 3.0.0.
#
# @safety
# This cop's autocorrection is unsafe because it's potentially dangerous.
# If using a stream, like `JSON.load(open('file'))`, you will need to call
# `#read` manually, like `JSON.parse(open('file').read)`.
# Other similar issues may apply.
#
# @example
# # bad
# JSON.load('{}')
# JSON.restore('{}')
#
# # good
# JSON.parse('{}')
# JSON.unsafe_load('{}')
#
# # good - explicit use of `create_additions` option
# JSON.load('{}', create_additions: true)
# JSON.load('{}', create_additions: false)
#
class JSONLoad < Base
extend AutoCorrector
MSG = 'Prefer `JSON.parse` over `JSON.%<method>s`.'
RESTRICT_ON_SEND = %i[load restore].freeze
# @!method insecure_json_load(node)
def_node_matcher :insecure_json_load, <<~PATTERN
(
send (const {nil? cbase} :JSON) ${:load :restore}
...
!(hash `(sym $:create_additions))
)
PATTERN
def on_send(node)
insecure_json_load(node) do |method|
add_offense(node.loc.selector, message: format(MSG, method: method)) do |corrector|
corrector.replace(node.loc.selector, 'parse')
end
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/bundler/gem_comment.rb | lib/rubocop/cop/bundler/gem_comment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Bundler
# Each gem in the Gemfile should have a comment explaining
# its purpose in the project, or the reason for its version
# or source.
#
# The optional "OnlyFor" configuration array
# can be used to only register offenses when the gems
# use certain options or have version specifiers.
#
# When "version_specifiers" is included, a comment
# will be enforced if the gem has any version specifier.
#
# When "restrictive_version_specifiers" is included, a comment
# will be enforced if the gem has a version specifier that
# holds back the version of the gem.
#
# For any other value in the array, a comment will be enforced for
# a gem if an option by the same name is present.
# A useful use case is to enforce a comment when using
# options that change the source of a gem:
#
# - `bitbucket`
# - `gist`
# - `git`
# - `github`
# - `source`
#
# For a full list of options supported by bundler,
# see https://bundler.io/man/gemfile.5.html
# .
#
# @example OnlyFor: [] (default)
# # bad
#
# gem 'foo'
#
# # good
#
# # Helpers for the foo things.
# gem 'foo'
#
# @example OnlyFor: ['version_specifiers']
# # bad
#
# gem 'foo', '< 2.1'
#
# # good
#
# # Version 2.1 introduces breaking change baz
# gem 'foo', '< 2.1'
#
# @example OnlyFor: ['restrictive_version_specifiers']
# # bad
#
# gem 'foo', '< 2.1'
#
# # good
#
# gem 'foo', '>= 1.0'
#
# # Version 2.1 introduces breaking change baz
# gem 'foo', '< 2.1'
#
# @example OnlyFor: ['version_specifiers', 'github']
# # bad
#
# gem 'foo', github: 'some_account/some_fork_of_foo'
#
# gem 'bar', '< 2.1'
#
# # good
#
# # Using this fork because baz
# gem 'foo', github: 'some_account/some_fork_of_foo'
#
# # Version 2.1 introduces breaking change baz
# gem 'bar', '< 2.1'
#
class GemComment < Base
include DefNode
include GemDeclaration
MSG = 'Missing gem description comment.'
CHECKED_OPTIONS_CONFIG = 'OnlyFor'
VERSION_SPECIFIERS_OPTION = 'version_specifiers'
RESTRICTIVE_VERSION_SPECIFIERS_OPTION = 'restrictive_version_specifiers'
RESTRICTIVE_VERSION_PATTERN = /\A\s*(?:<|~>|\d|=)/.freeze
RESTRICT_ON_SEND = %i[gem].freeze
def on_send(node)
return unless gem_declaration?(node)
return if ignored_gem?(node)
return if commented_any_descendant?(node)
return if cop_config[CHECKED_OPTIONS_CONFIG].any? && !checked_options_present?(node)
add_offense(node)
end
private
def commented_any_descendant?(node)
commented?(node) || node.each_descendant.any? { |n| commented?(n) }
end
def commented?(node)
preceding_lines = preceding_lines(node)
preceding_comment?(node, preceding_lines.last)
end
# The args node1 & node2 may represent a RuboCop::AST::Node
# or a Parser::Source::Comment. Both respond to #loc.
def precede?(node1, node2)
node2.loc.line - node1.loc.line <= 1
end
def preceding_lines(node)
processed_source.ast_with_comments[node].select do |line|
line.loc.line <= node.loc.line
end
end
def preceding_comment?(node1, node2)
node1 && node2 && precede?(node2, node1) && comment_line?(node2.source)
end
def ignored_gem?(node)
ignored_gems = Array(cop_config['IgnoredGems'])
ignored_gems.include?(node.first_argument.value)
end
def checked_options_present?(node)
(cop_config[CHECKED_OPTIONS_CONFIG].include?(VERSION_SPECIFIERS_OPTION) &&
version_specified_gem?(node)) ||
(cop_config[CHECKED_OPTIONS_CONFIG].include?(RESTRICTIVE_VERSION_SPECIFIERS_OPTION) &&
restrictive_version_specified_gem?(node)) ||
contains_checked_options?(node)
end
# Besides the gem name, all other *positional* arguments to `gem` are version specifiers,
# as long as it has one we know there's at least one version specifier.
def version_specified_gem?(node)
# arguments[0] is the gem name
node.arguments[1]&.str_type?
end
# Version specifications that restrict all updates going forward. This excludes versions
# like ">= 1.0" or "!= 2.0.3".
def restrictive_version_specified_gem?(node)
return false unless version_specified_gem?(node)
node.arguments[1..]
.any? { |arg| arg&.str_type? && RESTRICTIVE_VERSION_PATTERN.match?(arg.value) }
end
def contains_checked_options?(node)
(Array(cop_config[CHECKED_OPTIONS_CONFIG]) & gem_options(node).map(&:to_s)).any?
end
def gem_options(node)
return [] unless node.last_argument&.hash_type?
node.last_argument.keys.map(&:value)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/bundler/insecure_protocol_source.rb | lib/rubocop/cop/bundler/insecure_protocol_source.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Bundler
# Passing symbol arguments to `source` (e.g. `source :rubygems`) is
# deprecated because they default to using HTTP requests. Instead, specify
# `'https://rubygems.org'` if possible, or `'http://rubygems.org'` if not.
#
# When autocorrecting, this cop will replace symbol arguments with
# `'https://rubygems.org'`.
#
# This cop will not replace existing sources that use `http://`. This may
# be necessary where HTTPS is not available. For example, where using an
# internal gem server via an intranet, or where HTTPS is prohibited.
# However, you should strongly prefer `https://` where possible, as it is
# more secure.
#
# If you don't allow `http://`, please set `false` to `AllowHttpProtocol`.
# This option is `true` by default for safe autocorrection.
#
# @example
# # bad
# source :gemcutter
# source :rubygems
# source :rubyforge
#
# # good
# source 'https://rubygems.org' # strongly recommended
#
# @example AllowHttpProtocol: true (default)
#
# # good
# source 'http://rubygems.org' # use only if HTTPS is unavailable
#
# @example AllowHttpProtocol: false
#
# # bad
# source 'http://rubygems.org'
#
class InsecureProtocolSource < Base
extend AutoCorrector
MSG = 'The source `:%<source>s` is deprecated because HTTP requests ' \
'are insecure. ' \
"Please change your source to 'https://rubygems.org' " \
"if possible, or 'http://rubygems.org' if not."
MSG_HTTP_PROTOCOL = 'Use `https://rubygems.org` instead of `http://rubygems.org`.'
RESTRICT_ON_SEND = %i[source].freeze
# @!method insecure_protocol_source?(node)
def_node_matcher :insecure_protocol_source?, <<~PATTERN
(send nil? :source
${(sym :gemcutter) (sym :rubygems) (sym :rubyforge) (:str "http://rubygems.org")})
PATTERN
def on_send(node)
insecure_protocol_source?(node) do |source_node|
source = source_node.value
use_http_protocol = source == 'http://rubygems.org'
return if allow_http_protocol? && use_http_protocol
message = if use_http_protocol
MSG_HTTP_PROTOCOL
else
format(MSG, source: source)
end
add_offense(source_node, message: message) do |corrector|
corrector.replace(source_node, "'https://rubygems.org'")
end
end
end
private
def allow_http_protocol?
cop_config.fetch('AllowHttpProtocol', true)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/bundler/ordered_gems.rb | lib/rubocop/cop/bundler/ordered_gems.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Bundler
# Gems should be alphabetically sorted within groups.
#
# @example
# # bad
# gem 'rubocop'
# gem 'rspec'
#
# # good
# gem 'rspec'
# gem 'rubocop'
#
# # good
# gem 'rubocop'
#
# gem 'rspec'
#
# @example TreatCommentsAsGroupSeparators: true (default)
# # good
# # For code quality
# gem 'rubocop'
# # For tests
# gem 'rspec'
#
# @example TreatCommentsAsGroupSeparators: false
# # bad
# # For code quality
# gem 'rubocop'
# # For tests
# gem 'rspec'
class OrderedGems < Base
extend AutoCorrector
include OrderedGemNode
MSG = 'Gems should be sorted in an alphabetical order within their ' \
'section of the Gemfile. ' \
'Gem `%<previous>s` should appear before `%<current>s`.'
def on_new_investigation
return if processed_source.blank?
gem_declarations(processed_source.ast).each_cons(2) do |previous, current|
next unless consecutive_lines?(previous, current)
next unless case_insensitive_out_of_order?(gem_name(current), gem_name(previous))
register_offense(previous, current)
end
end
private
def previous_declaration(node)
declarations = gem_declarations(processed_source.ast)
node_index = declarations.map(&:location).find_index(node.location)
declarations.to_a[node_index - 1]
end
# @!method gem_declarations(node)
def_node_search :gem_declarations, <<~PATTERN
(:send nil? :gem str ...)
PATTERN
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/bundler/duplicated_gem.rb | lib/rubocop/cop/bundler/duplicated_gem.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Bundler
# A Gem's requirements should be listed only once in a Gemfile.
#
# @example
# # bad
# gem 'rubocop'
# gem 'rubocop'
#
# # bad
# group :development do
# gem 'rubocop'
# end
#
# group :test do
# gem 'rubocop'
# end
#
# # good
# group :development, :test do
# gem 'rubocop'
# end
#
# # good
# gem 'rubocop', groups: [:development, :test]
#
# # good - conditional declaration
# if Dir.exist?(local)
# gem 'rubocop', path: local
# elsif ENV['RUBOCOP_VERSION'] == 'master'
# gem 'rubocop', git: 'https://github.com/rubocop/rubocop.git'
# else
# gem 'rubocop', '~> 0.90.0'
# end
#
class DuplicatedGem < Base
include RangeHelp
MSG = 'Gem `%<gem_name>s` requirements already given on line ' \
'%<line_of_first_occurrence>d of the Gemfile.'
def on_new_investigation
return if processed_source.blank?
duplicated_gem_nodes.each do |nodes|
nodes[1..].each do |node|
register_offense(node, node.first_argument.to_a.first, nodes.first.first_line)
end
end
end
private
# @!method gem_declarations(node)
def_node_search :gem_declarations, '(send nil? :gem str ...)'
def duplicated_gem_nodes
gem_declarations(processed_source.ast)
.group_by(&:first_argument)
.values
.select { |nodes| nodes.size > 1 && !conditional_declaration?(nodes) }
end
def conditional_declaration?(nodes)
parent = nodes[0].each_ancestor.find { |ancestor| !ancestor.begin_type? }
return false unless parent&.type?(:if, :when)
root_conditional_node = parent.if_type? ? parent : parent.parent
nodes.all? { |node| within_conditional?(node, root_conditional_node) }
end
def within_conditional?(node, conditional_node)
conditional_node.branches.compact.any? do |branch|
branch == node || branch.child_nodes.include?(node)
end
end
def register_offense(node, gem_name, line_of_first_occurrence)
line_range = node.loc.column...node.loc.last_column
offense_location = source_range(processed_source.buffer, node.first_line, line_range)
message = format(
MSG,
gem_name: gem_name,
line_of_first_occurrence: line_of_first_occurrence
)
add_offense(offense_location, message: message)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/bundler/gem_filename.rb | lib/rubocop/cop/bundler/gem_filename.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Bundler
# Verifies that a project contains Gemfile or gems.rb file and correct
# associated lock file based on the configuration.
#
# @example EnforcedStyle: Gemfile (default)
# # bad
# Project contains gems.rb and gems.locked files
#
# # bad
# Project contains Gemfile and gems.locked file
#
# # good
# Project contains Gemfile and Gemfile.lock
#
# @example EnforcedStyle: gems.rb
# # bad
# Project contains Gemfile and Gemfile.lock files
#
# # bad
# Project contains gems.rb and Gemfile.lock file
#
# # good
# Project contains gems.rb and gems.locked files
class GemFilename < Base
include ConfigurableEnforcedStyle
MSG_GEMFILE_REQUIRED = '`gems.rb` file was found but `Gemfile` is required ' \
'(file path: %<file_path>s).'
MSG_GEMS_RB_REQUIRED = '`Gemfile` was found but `gems.rb` file is required ' \
'(file path: %<file_path>s).'
MSG_GEMFILE_MISMATCHED = 'Expected a `Gemfile.lock` with `Gemfile` but found ' \
'`gems.locked` file (file path: %<file_path>s).'
MSG_GEMS_RB_MISMATCHED = 'Expected a `gems.locked` file with `gems.rb` but found ' \
'`Gemfile.lock` (file path: %<file_path>s).'
GEMFILE_FILES = %w[Gemfile Gemfile.lock].freeze
GEMS_RB_FILES = %w[gems.rb gems.locked].freeze
def on_new_investigation
file_path = processed_source.file_path
basename = File.basename(file_path)
return if expected_gemfile?(basename)
register_offense(file_path, basename)
end
private
def register_offense(file_path, basename)
register_gemfile_offense(file_path, basename) if gemfile_offense?(basename)
register_gems_rb_offense(file_path, basename) if gems_rb_offense?(basename)
end
def register_gemfile_offense(file_path, basename)
message = case basename
when 'gems.rb'
MSG_GEMFILE_REQUIRED
when 'gems.locked'
MSG_GEMFILE_MISMATCHED
end
add_global_offense(format(message, file_path: file_path))
end
def register_gems_rb_offense(file_path, basename)
message = case basename
when 'Gemfile'
MSG_GEMS_RB_REQUIRED
when 'Gemfile.lock'
MSG_GEMS_RB_MISMATCHED
end
add_global_offense(format(message, file_path: file_path))
end
def gemfile_offense?(basename)
gemfile_required? && GEMS_RB_FILES.include?(basename)
end
def gems_rb_offense?(basename)
gems_rb_required? && GEMFILE_FILES.include?(basename)
end
def expected_gemfile?(basename)
(gemfile_required? && GEMFILE_FILES.include?(basename)) ||
(gems_rb_required? && GEMS_RB_FILES.include?(basename))
end
def gemfile_required?
style == :Gemfile
end
def gems_rb_required?
style == :'gems.rb'
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/bundler/gem_version.rb | lib/rubocop/cop/bundler/gem_version.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Bundler
# Enforce that Gem version specifications or a commit reference (branch,
# ref, or tag) are either required or forbidden.
#
# @example EnforcedStyle: required (default)
# # bad
# gem 'rubocop'
#
# # good
# gem 'rubocop', '~> 1.12'
#
# # good
# gem 'rubocop', '>= 1.10.0'
#
# # good
# gem 'rubocop', '>= 1.5.0', '< 1.10.0'
#
# # good
# gem 'rubocop', branch: 'feature-branch'
#
# # good
# gem 'rubocop', ref: '74b5bfbb2c4b6fd6cdbbc7254bd7084b36e0c85b'
#
# # good
# gem 'rubocop', tag: 'v1.17.0'
#
# @example EnforcedStyle: forbidden
# # good
# gem 'rubocop'
#
# # bad
# gem 'rubocop', '~> 1.12'
#
# # bad
# gem 'rubocop', '>= 1.10.0'
#
# # bad
# gem 'rubocop', '>= 1.5.0', '< 1.10.0'
#
# # bad
# gem 'rubocop', branch: 'feature-branch'
#
# # bad
# gem 'rubocop', ref: '74b5bfbb2c4b6fd6cdbbc7254bd7084b36e0c85b'
#
# # bad
# gem 'rubocop', tag: 'v1.17.0'
#
class GemVersion < Base
include ConfigurableEnforcedStyle
include GemDeclaration
REQUIRED_MSG = 'Gem version specification is required.'
FORBIDDEN_MSG = 'Gem version specification is forbidden.'
RESTRICT_ON_SEND = %i[gem].freeze
VERSION_SPECIFICATION_REGEX = /^\s*[~<>=]*\s*[0-9.]+/.freeze
# @!method includes_version_specification?(node)
def_node_matcher :includes_version_specification?, <<~PATTERN
(send nil? :gem <(str #version_specification?) ...>)
PATTERN
# @!method includes_commit_reference?(node)
def_node_matcher :includes_commit_reference?, <<~PATTERN
(send nil? :gem <(hash <(pair (sym {:branch :ref :tag}) (str _)) ...>) ...>)
PATTERN
def on_send(node)
return unless gem_declaration?(node)
return if allowed_gem?(node)
if offense?(node)
add_offense(node)
opposite_style_detected
else
correct_style_detected
end
end
private
def allowed_gem?(node)
allowed_gems.include?(node.first_argument.value)
end
def allowed_gems
Array(cop_config['AllowedGems'])
end
def message(_range)
if required_style?
REQUIRED_MSG
elsif forbidden_style?
FORBIDDEN_MSG
end
end
def offense?(node)
required_offense?(node) || forbidden_offense?(node)
end
def required_offense?(node)
return false unless required_style?
!includes_version_specification?(node) && !includes_commit_reference?(node)
end
def forbidden_offense?(node)
return false unless forbidden_style?
includes_version_specification?(node) || includes_commit_reference?(node)
end
def forbidden_style?
style == :forbidden
end
def required_style?
style == :required
end
def version_specification?(expression)
expression.match?(VERSION_SPECIFICATION_REGEX)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/bundler/duplicated_group.rb | lib/rubocop/cop/bundler/duplicated_group.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Bundler
# A Gem group, or a set of groups, should be listed only once in a Gemfile.
#
# For example, if the values of `source`, `git`, `platforms`, or `path`
# surrounding `group` are different, no offense will be registered:
#
# [source,ruby]
# -----
# platforms :ruby do
# group :default do
# gem 'openssl'
# end
# end
#
# platforms :jruby do
# group :default do
# gem 'jruby-openssl'
# end
# end
# -----
#
# @example
# # bad
# group :development do
# gem 'rubocop'
# end
#
# group :development do
# gem 'rubocop-rails'
# end
#
# # bad (same set of groups declared twice)
# group :development, :test do
# gem 'rubocop'
# end
#
# group :test, :development do
# gem 'rspec'
# end
#
# # good
# group :development do
# gem 'rubocop'
# end
#
# group :development, :test do
# gem 'rspec'
# end
#
# # good
# gem 'rubocop', groups: [:development, :test]
# gem 'rspec', groups: [:development, :test]
#
class DuplicatedGroup < Base
include RangeHelp
MSG = 'Gem group `%<group_name>s` already defined on line ' \
'%<line_of_first_occurrence>d of the Gemfile.'
SOURCE_BLOCK_NAMES = %i[source git platforms path].freeze
# @!method group_declarations(node)
def_node_search :group_declarations, '(send nil? :group ...)'
def on_new_investigation
return if processed_source.blank?
duplicated_group_nodes.each do |nodes|
nodes[1..].each do |node|
group_name = node.arguments.map(&:source).join(', ')
register_offense(node, group_name, nodes.first.first_line)
end
end
end
private
def duplicated_group_nodes
group_declarations = group_declarations(processed_source.ast)
group_keys = group_declarations.group_by do |node|
source_key = find_source_key(node)
group_attributes = group_attributes(node).sort.join
"#{source_key}#{group_attributes}"
end
group_keys.values.select { |nodes| nodes.size > 1 }
end
def register_offense(node, group_name, line_of_first_occurrence)
line_range = node.loc.column...node.loc.last_column
offense_location = source_range(processed_source.buffer, node.first_line, line_range)
message = format(
MSG,
group_name: group_name,
line_of_first_occurrence: line_of_first_occurrence
)
add_offense(offense_location, message: message)
end
def find_source_key(node)
source_block = node.each_ancestor(:block).find do |block_node|
SOURCE_BLOCK_NAMES.include?(block_node.method_name)
end
return unless source_block
"#{source_block.method_name}#{source_block.send_node.first_argument&.source}"
end
def group_attributes(node)
node.arguments.map do |argument|
if argument.hash_type?
argument.pairs.map(&:source).sort.join(', ')
else
argument.respond_to?(:value) ? argument.value.to_s : argument.source
end
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/method_name.rb | lib/rubocop/cop/naming/method_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Makes sure that all methods use the configured style,
# snake_case or camelCase, for their names.
#
# Method names matching patterns are always allowed.
#
# The cop can be configured with `AllowedPatterns` to allow certain regexp patterns:
#
# [source,yaml]
# ----
# Naming/MethodName:
# AllowedPatterns:
# - '\AonSelectionBulkChange\z'
# - '\AonSelectionCleared\z'
# ----
#
# As well, you can also forbid specific method names or regexp patterns
# using `ForbiddenIdentifiers` or `ForbiddenPatterns`:
#
# [source,yaml]
# ----
# Naming/MethodName:
# ForbiddenIdentifiers:
# - 'def'
# - 'super'
# ForbiddenPatterns:
# - '_v1\z'
# - '_gen1\z'
# ----
#
# @example EnforcedStyle: snake_case (default)
# # bad
# def fooBar; end
#
# # good
# def foo_bar; end
#
# # bad
# define_method :fooBar do
# end
#
# # good
# define_method :foo_bar do
# end
#
# # bad
# Struct.new(:fooBar)
#
# # good
# Struct.new(:foo_bar)
#
# # bad
# alias_method :fooBar, :some_method
#
# # good
# alias_method :foo_bar, :some_method
#
# @example EnforcedStyle: camelCase
# # bad
# def foo_bar; end
#
# # good
# def fooBar; end
#
# # bad
# define_method :foo_bar do
# end
#
# # good
# define_method :fooBar do
# end
#
# # bad
# Struct.new(:foo_bar)
#
# # good
# Struct.new(:fooBar)
#
# # bad
# alias_method :foo_bar, :some_method
#
# # good
# alias_method :fooBar, :some_method
#
# @example ForbiddenIdentifiers: ['def', 'super']
# # bad
# def def; end
# def super; end
#
# @example ForbiddenPatterns: ['_v1\z', '_gen1\z']
# # bad
# def release_v1; end
# def api_gen1; end
#
class MethodName < Base
include ConfigurableNaming
include AllowedPattern
include RangeHelp
include ForbiddenIdentifiers
include ForbiddenPattern
MSG = 'Use %<style>s for method names.'
MSG_FORBIDDEN = '`%<identifier>s` is forbidden, use another method name instead.'
OPERATOR_METHODS = %i[| ^ & <=> == === =~ > >= < <= << >> + - * /
% ** ~ +@ -@ !@ ~@ [] []= ! != !~ `].to_set.freeze
# @!method sym_name(node)
def_node_matcher :sym_name, '(sym $_name)'
# @!method str_name(node)
def_node_matcher :str_name, '(str $_name)'
# @!method new_struct?(node)
def_node_matcher :new_struct?, '(send (const {nil? cbase} :Struct) :new ...)'
# @!method define_data?(node)
def_node_matcher :define_data?, '(send (const {nil? cbase} :Data) :define ...)'
def on_send(node)
if node.method?(:define_method) || node.method?(:define_singleton_method)
handle_define_method(node)
elsif new_struct?(node)
handle_new_struct(node)
elsif define_data?(node)
handle_define_data(node)
elsif node.method?(:alias_method)
handle_alias_method(node)
else
handle_attr_accessor(node)
end
end
def on_def(node)
return if node.operator_method? || matches_allowed_pattern?(node.method_name)
if forbidden_name?(node.method_name.to_s)
register_forbidden_name(node)
else
check_name(node, node.method_name, node.loc.name)
end
end
alias on_defs on_def
def on_alias(node)
return unless (new_identifier = node.new_identifier).sym_type?
handle_method_name(new_identifier, new_identifier.value)
end
private
def handle_define_method(node)
return unless node.first_argument&.type?(:str, :sym)
handle_method_name(node, node.first_argument.value)
end
def handle_new_struct(node)
arguments = node.first_argument&.str_type? ? node.arguments[1..] : node.arguments
arguments.select { |argument| argument.type?(:sym, :str) }.each do |name|
handle_method_name(name, name.value)
end
end
def handle_define_data(node)
node.arguments.select { |argument| argument.type?(:sym, :str) }.each do |name|
handle_method_name(name, name.value)
end
end
def handle_alias_method(node)
return unless node.arguments.size == 2
return unless node.first_argument.type?(:str, :sym)
handle_method_name(node.first_argument, node.first_argument.value)
end
def handle_attr_accessor(node)
return unless (attrs = node.attribute_accessor?)
attrs.last.each do |name_item|
name = attr_name(name_item)
next if !name || matches_allowed_pattern?(name)
if forbidden_name?(name.to_s)
register_forbidden_name(node)
else
check_name(node, name, range_position(node))
end
end
end
def handle_method_name(node, name)
return if !name || matches_allowed_pattern?(name)
if forbidden_name?(name.to_s)
register_forbidden_name(node)
elsif !OPERATOR_METHODS.include?(name.to_sym)
check_name(node, name, range_position(node))
end
end
def forbidden_name?(name)
forbidden_identifier?(name) || forbidden_pattern?(name)
end
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize
def register_forbidden_name(node)
if node.any_def_type?
name_node = node.loc.name
method_name = node.method_name
elsif node.literal?
name_node = node
method_name = node.value
elsif (attrs = node.attribute_accessor?)
name_node = attrs.last.last
method_name = attr_name(name_node)
else
name_node = node.first_argument
method_name = node.first_argument.value
end
message = format(MSG_FORBIDDEN, identifier: method_name)
add_offense(name_node, message: message)
end
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
def attr_name(name_item)
sym_name(name_item) || str_name(name_item)
end
def range_position(node)
if node.loc?(:selector)
selector_end_pos = node.loc.selector.end_pos + 1
expr_end_pos = node.source_range.end_pos
range_between(selector_end_pos, expr_end_pos)
else
node.source_range
end
end
def message(style)
format(MSG, style: style)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/accessor_method_name.rb | lib/rubocop/cop/naming/accessor_method_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Avoid prefixing accessor method names with `get_` or `set_`.
# Applies to both instance and class methods.
#
# NOTE: Method names starting with `get_` or `set_` only register an offense
# when the methods match the expected arity for getters and setters respectively.
# Getters (`get_attribute`) must have no arguments to be registered,
# and setters (`set_attribute(value)`) must have exactly one.
#
# @example
# # bad
# def set_attribute(value)
# end
#
# # good
# def attribute=(value)
# end
#
# # bad
# def get_attribute
# end
#
# # good
# def attribute
# end
#
# # accepted, incorrect arity for getter
# def get_value(attr)
# end
#
# # accepted, incorrect arity for setter
# def set_value
# end
class AccessorMethodName < Base
MSG_READER = 'Do not prefix reader method names with `get_`.'
MSG_WRITER = 'Do not prefix writer method names with `set_`.'
def on_def(node)
return unless proper_attribute_name?(node)
return unless bad_reader_name?(node) || bad_writer_name?(node)
message = message(node)
add_offense(node.loc.name, message: message)
end
alias on_defs on_def
private
def message(node)
if bad_reader_name?(node)
MSG_READER
elsif bad_writer_name?(node)
MSG_WRITER
end
end
def proper_attribute_name?(node)
!node.method_name.to_s.end_with?('!', '?', '=')
end
def bad_reader_name?(node)
node.method_name.to_s.start_with?('get_') && !node.arguments?
end
def bad_writer_name?(node)
node.method_name.to_s.start_with?('set_') &&
node.arguments.one? &&
node.first_argument.arg_type?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/block_parameter_name.rb | lib/rubocop/cop/naming/block_parameter_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks block parameter names for how descriptive they
# are. It is highly configurable.
#
# The `MinNameLength` config option takes an integer. It represents
# the minimum amount of characters the name must be. Its default is 1.
# The `AllowNamesEndingInNumbers` config option takes a boolean. When
# set to false, this cop will register offenses for names ending with
# numbers. Its default is false. The `AllowedNames` config option
# takes an array of permitted names that will never register an
# offense. The `ForbiddenNames` config option takes an array of
# restricted names that will always register an offense.
#
# @example
# # bad
# bar do |varOne, varTwo|
# varOne + varTwo
# end
#
# # With `AllowNamesEndingInNumbers` set to false
# foo { |num1, num2| num1 * num2 }
#
# # With `MinNameLength` set to number greater than 1
# baz { |a, b, c| do_stuff(a, b, c) }
#
# # good
# bar do |thud, fred|
# thud + fred
# end
#
# foo { |speed, distance| speed * distance }
#
# baz { |age, height, gender| do_stuff(age, height, gender) }
class BlockParameterName < Base
include UncommunicativeName
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
return unless node.arguments?
check(node, node.arguments)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/method_parameter_name.rb | lib/rubocop/cop/naming/method_parameter_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks method parameter names for how descriptive they
# are. It is highly configurable.
#
# The `MinNameLength` config option takes an integer. It represents
# the minimum amount of characters the name must be. Its default is 3.
# The `AllowNamesEndingInNumbers` config option takes a boolean. When
# set to false, this cop will register offenses for names ending with
# numbers. Its default is false. The `AllowedNames` config option
# takes an array of permitted names that will never register an
# offense. The `ForbiddenNames` config option takes an array of
# restricted names that will always register an offense.
#
# @example
# # bad
# def bar(varOne, varTwo)
# varOne + varTwo
# end
#
# # With `AllowNamesEndingInNumbers` set to false
# def foo(num1, num2)
# num1 * num2
# end
#
# # With `MinNameLength` set to number greater than 1
# def baz(a, b, c)
# do_stuff(a, b, c)
# end
#
# # good
# def bar(thud, fred)
# thud + fred
# end
#
# def foo(speed, distance)
# speed * distance
# end
#
# def baz(age_a, height_b, gender_c)
# do_stuff(age_a, height_b, gender_c)
# end
class MethodParameterName < Base
include UncommunicativeName
def on_def(node)
return unless node.arguments?
check(node, node.arguments)
end
alias on_defs on_def
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/rescued_exceptions_variable_name.rb | lib/rubocop/cop/naming/rescued_exceptions_variable_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Makes sure that rescued exceptions variables are named as
# expected.
#
# The `PreferredName` config option takes a `String`. It represents
# the required name of the variable. Its default is `e`.
#
# NOTE: This cop does not consider nested rescues because it cannot
# guarantee that the variable from the outer rescue is not used within
# the inner rescue (in which case, changing the inner variable would
# shadow the outer variable).
#
# @example PreferredName: e (default)
# # bad
# begin
# # do something
# rescue MyException => exception
# # do something
# end
#
# # good
# begin
# # do something
# rescue MyException => e
# # do something
# end
#
# # good
# begin
# # do something
# rescue MyException => _e
# # do something
# end
#
# @example PreferredName: exception
# # bad
# begin
# # do something
# rescue MyException => e
# # do something
# end
#
# # good
# begin
# # do something
# rescue MyException => exception
# # do something
# end
#
# # good
# begin
# # do something
# rescue MyException => _exception
# # do something
# end
#
class RescuedExceptionsVariableName < Base
extend AutoCorrector
MSG = 'Use `%<preferred>s` instead of `%<bad>s`.'
def on_resbody(node)
offending_name = variable_name(node)
return unless offending_name
# Handle nested rescues by only requiring the outer one to use the
# configured variable name, so that nested rescues don't use the same
# variable.
return if node.each_ancestor(:resbody).any?
preferred_name = preferred_name(offending_name)
return if preferred_name.to_sym == offending_name
# check variable shadowing for exception variable
return if shadowed_variable_name?(node)
range = offense_range(node)
message = message(node)
add_offense(range, message: message) do |corrector|
autocorrect(corrector, node, range, offending_name, preferred_name)
end
end
private
def offense_range(resbody)
variable = resbody.exception_variable
variable.source_range
end
def autocorrect(corrector, node, range, offending_name, preferred_name)
corrector.replace(range, preferred_name)
correct_node(corrector, node.body, offending_name, preferred_name)
return unless (kwbegin_node = node.parent.each_ancestor(:kwbegin).first)
kwbegin_node.right_siblings.each do |child_node|
correct_node(corrector, child_node, offending_name, preferred_name)
end
end
def variable_name_matches?(node, name)
if node.masgn_type?
node.each_descendant(:lvasgn).any? do |lvasgn_node|
variable_name_matches?(lvasgn_node, name)
end
else
node.name == name
end
end
# rubocop:disable Metrics/MethodLength
def correct_node(corrector, node, offending_name, preferred_name)
return unless node
node.each_node(:lvar, :lvasgn, :masgn) do |child_node|
next unless variable_name_matches?(child_node, offending_name)
if child_node.lvar_type?
parent_node = child_node.parent
if parent_node.respond_to?(:value_omission?) && parent_node.value_omission?
corrector.insert_after(parent_node.loc.operator, " #{preferred_name}")
else
corrector.replace(child_node, preferred_name)
end
end
if child_node.type?(:masgn, :lvasgn)
correct_reassignment(corrector, child_node, offending_name, preferred_name)
break
end
end
end
# rubocop:enable Metrics/MethodLength
# If the exception variable is reassigned, that assignment needs to be corrected.
# Further `lvar` nodes will not be corrected though since they now refer to a
# different variable.
def correct_reassignment(corrector, node, offending_name, preferred_name)
correct_node(corrector, node.rhs, offending_name, preferred_name)
end
def preferred_name(variable_name)
preferred_name = cop_config.fetch('PreferredName', 'e')
if variable_name.to_s.start_with?('_')
"_#{preferred_name}"
else
preferred_name
end
end
def variable_name(node)
node.exception_variable.name if node.exception_variable.respond_to?(:name)
end
def message(node)
offending_name = variable_name(node)
preferred_name = preferred_name(offending_name)
format(MSG, preferred: preferred_name, bad: offending_name)
end
def shadowed_variable_name?(node)
node.each_descendant(:lvar).any? { |n| n.children.first.to_s == preferred_name(n) }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/heredoc_delimiter_naming.rb | lib/rubocop/cop/naming/heredoc_delimiter_naming.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks that your heredocs are using meaningful delimiters.
# By default it disallows `END` and `EO*`, and can be configured through
# forbidden listing additional delimiters.
#
# @example
#
# # good
# <<-SQL
# SELECT * FROM foo
# SQL
#
# # bad
# <<-END
# SELECT * FROM foo
# END
#
# # bad
# <<-EOS
# SELECT * FROM foo
# EOS
class HeredocDelimiterNaming < Base
include Heredoc
MSG = 'Use meaningful heredoc delimiters.'
def on_heredoc(node)
return if meaningful_delimiters?(node)
range = node.children.empty? ? node : node.loc.heredoc_end
add_offense(range)
end
private
def meaningful_delimiters?(node)
delimiters = delimiter_string(node)
return false unless /\w/.match?(delimiters)
forbidden_delimiters.none? do |forbidden_delimiter|
Regexp.new(forbidden_delimiter).match?(delimiters)
end
end
def forbidden_delimiters
cop_config['ForbiddenDelimiters'] || []
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/variable_name.rb | lib/rubocop/cop/naming/variable_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks that the configured style (snake_case or camelCase) is used for all variable names.
# This includes local variables, instance variables, class variables, method arguments
# (positional, keyword, rest or block), and block arguments.
#
# The cop can also be configured to forbid using specific names for variables, using
# `ForbiddenIdentifiers` or `ForbiddenPatterns`. In addition to the above, this applies
# to global variables as well.
#
# Method definitions and method calls are not affected by this cop.
#
# @example EnforcedStyle: snake_case (default)
# # bad
# fooBar = 1
#
# # good
# foo_bar = 1
#
# @example EnforcedStyle: camelCase
# # bad
# foo_bar = 1
#
# # good
# fooBar = 1
#
# @example AllowedIdentifiers: ['fooBar']
# # good (with EnforcedStyle: snake_case)
# fooBar = 1
#
# @example AllowedPatterns: ['_v\d+\z']
# # good (with EnforcedStyle: camelCase)
# release_v1 = true
#
# @example ForbiddenIdentifiers: ['fooBar']
# # bad (in all cases)
# fooBar = 1
# @fooBar = 1
# @@fooBar = 1
# $fooBar = 1
#
# @example ForbiddenPatterns: ['_v\d+\z']
# # bad (in all cases)
# release_v1 = true
# @release_v1 = true
# @@release_v1 = true
# $release_v1 = true
#
class VariableName < Base
include AllowedIdentifiers
include ConfigurableNaming
include AllowedPattern
include ForbiddenIdentifiers
include ForbiddenPattern
MSG = 'Use %<style>s for variable names.'
MSG_FORBIDDEN = '`%<identifier>s` is forbidden, use another name instead.'
def valid_name?(node, name, given_style = style)
super || matches_allowed_pattern?(name)
end
def on_lvasgn(node)
return unless (name = node.name)
return if allowed_identifier?(name)
if forbidden_name?(name)
register_forbidden_name(node)
else
check_name(node, name, node.loc.name)
end
end
alias on_ivasgn on_lvasgn
alias on_cvasgn on_lvasgn
alias on_arg on_lvasgn
alias on_optarg on_lvasgn
alias on_restarg on_lvasgn
alias on_kwoptarg on_lvasgn
alias on_kwarg on_lvasgn
alias on_kwrestarg on_lvasgn
alias on_blockarg on_lvasgn
alias on_lvar on_lvasgn
# Only forbidden names are checked for global variable assignment
def on_gvasgn(node)
return unless (name = node.name)
return unless forbidden_name?(name)
register_forbidden_name(node)
end
private
def forbidden_name?(name)
forbidden_identifier?(name) || forbidden_pattern?(name)
end
def message(style)
format(MSG, style: style)
end
def register_forbidden_name(node)
message = format(MSG_FORBIDDEN, identifier: node.name)
add_offense(node.loc.name, message: message)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/ascii_identifiers.rb | lib/rubocop/cop/naming/ascii_identifiers.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks for non-ascii characters in identifier and constant names.
# Identifiers are always checked and whether constants are checked
# can be controlled using AsciiConstants config.
#
# @example
# # bad
# def καλημερα # Greek alphabet (non-ascii)
# end
#
# # bad
# def こんにちはと言う # Japanese character (non-ascii)
# end
#
# # bad
# def hello_🍣 # Emoji (non-ascii)
# end
#
# # good
# def say_hello
# end
#
# # bad
# 신장 = 10 # Hangul character (non-ascii)
#
# # good
# height = 10
#
# # bad
# params[:عرض_gteq] # Arabic character (non-ascii)
#
# # good
# params[:width_gteq]
#
# @example AsciiConstants: true (default)
# # bad
# class Foö
# end
#
# FOÖ = "foo"
#
# @example AsciiConstants: false
# # good
# class Foö
# end
#
# FOÖ = "foo"
#
class AsciiIdentifiers < Base
include RangeHelp
IDENTIFIER_MSG = 'Use only ascii symbols in identifiers.'
CONSTANT_MSG = 'Use only ascii symbols in constants.'
def on_new_investigation
processed_source.tokens.each do |token|
next if !should_check?(token) || token.text.ascii_only?
message = token.type == :tIDENTIFIER ? IDENTIFIER_MSG : CONSTANT_MSG
add_offense(first_offense_range(token), message: message)
end
end
private
def should_check?(token)
token.type == :tIDENTIFIER || (token.type == :tCONSTANT && cop_config['AsciiConstants'])
end
def first_offense_range(identifier)
expression = identifier.pos
first_offense = first_non_ascii_chars(identifier.text)
start_position = expression.begin_pos + identifier.text.index(first_offense)
end_position = start_position + first_offense.length
range_between(start_position, end_position)
end
def first_non_ascii_chars(string)
string.match(/[^[:ascii:]]+/).to_s
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/file_name.rb | lib/rubocop/cop/naming/file_name.rb | # frozen_string_literal: true
require 'pathname'
module RuboCop
module Cop
module Naming
# Makes sure that Ruby source files have snake_case
# names. Ruby scripts (i.e. source files with a shebang in the
# first line) are ignored.
#
# The cop also ignores `.gemspec` files, because Bundler
# recommends using dashes to separate namespaces in nested gems
# (i.e. `bundler-console` becomes `Bundler::Console`). As such, the
# gemspec is supposed to be named `bundler-console.gemspec`.
#
# When `ExpectMatchingDefinition` (default: `false`) is `true`, the cop requires
# each file to have a class, module or `Struct` defined in it that matches
# the filename. This can be further configured using
# `CheckDefinitionPathHierarchy` (default: `true`) to determine whether the
# path should match the namespace of the above definition.
#
# When `IgnoreExecutableScripts` (default: `true`) is `true`, files that start
# with a shebang line are not considered by the cop.
#
# When `Regex` is set, the cop will flag any filename that does not match
# the regular expression.
#
# @example
# # bad
# lib/layoutManager.rb
#
# anything/usingCamelCase
#
# # good
# lib/layout_manager.rb
#
# anything/using_snake_case.rake
class FileName < Base
MSG_SNAKE_CASE = 'The name of this source file (`%<basename>s`) should use snake_case.'
MSG_NO_DEFINITION = '`%<basename>s` should define a class or module called `%<namespace>s`.'
MSG_REGEX = '`%<basename>s` should match `%<regex>s`.'
SNAKE_CASE = /^[\d[[:lower:]]_.?!]+$/.freeze
# @!method struct_definition(node)
def_node_matcher :struct_definition, <<~PATTERN
{
(casgn $_ $_ (send (const {nil? cbase} :Struct) :new ...))
(casgn $_ $_ (block (send (const {nil? cbase} :Struct) :new ...) ...))
}
PATTERN
def on_new_investigation
file_path = processed_source.file_path
return if config.file_to_exclude?(file_path) || config.allowed_camel_case_file?(file_path)
for_bad_filename(file_path)
end
private
def for_bad_filename(file_path)
basename = File.basename(file_path)
if filename_good?(basename)
msg = perform_class_and_module_naming_checks(file_path, basename)
else
msg = other_message(basename) unless bad_filename_allowed?
end
add_global_offense(msg) if msg
end
def perform_class_and_module_naming_checks(file_path, basename)
return unless expect_matching_definition?
if check_definition_path_hierarchy? && !matching_definition?(file_path)
msg = no_definition_message(basename, file_path)
elsif !matching_class?(basename)
msg = no_definition_message(basename, basename)
end
msg
end
def matching_definition?(file_path)
find_class_or_module(processed_source.ast, to_namespace(file_path))
end
def matching_class?(file_name)
find_class_or_module(processed_source.ast, to_namespace(file_name))
end
def bad_filename_allowed?
ignore_executable_scripts? && processed_source.start_with?('#!')
end
def no_definition_message(basename, file_path)
format(MSG_NO_DEFINITION,
basename: basename,
namespace: to_namespace(file_path).join('::'))
end
def other_message(basename)
if regex
format(MSG_REGEX, basename: basename, regex: regex)
else
format(MSG_SNAKE_CASE, basename: basename)
end
end
def ignore_executable_scripts?
cop_config['IgnoreExecutableScripts']
end
def expect_matching_definition?
cop_config['ExpectMatchingDefinition']
end
def check_definition_path_hierarchy?
cop_config['CheckDefinitionPathHierarchy']
end
def definition_path_hierarchy_roots
cop_config['CheckDefinitionPathHierarchyRoots'] || []
end
def regex
cop_config['Regex']
end
def allowed_acronyms
cop_config['AllowedAcronyms'] || []
end
def filename_good?(basename)
basename = basename.delete_prefix('.')
basename = basename.sub(/\.[^.]+$/, '')
# special handling for Action Pack Variants file names like
# some_file.xlsx+mobile.axlsx
basename = basename.sub('+', '_')
basename.match?(regex || SNAKE_CASE)
end
def find_class_or_module(node, namespace)
return nil unless node
name = namespace.pop
on_node(%i[class module casgn], node) do |child|
next unless (const = find_definition(child))
const_namespace, const_name = *const
next if name != const_name && !match_acronym?(name, const_name)
next unless namespace.empty? || namespace_matches?(child, const_namespace, namespace)
return node
end
nil
end
def find_definition(node)
node.defined_module || defined_struct(node)
end
def defined_struct(node)
namespace, name = *struct_definition(node)
s(:const, namespace, name) if name
end
def namespace_matches?(node, namespace, expected)
match_partial = partial_matcher!(expected)
match_partial.call(namespace)
node.each_ancestor(:class, :module, :sclass, :casgn) do |ancestor|
return false if ancestor.sclass_type?
match_partial.call(ancestor.defined_module)
end
match?(expected)
end
def partial_matcher!(expected)
lambda do |namespace|
while namespace
return match?(expected) if namespace.cbase_type?
namespace, name = *namespace
expected.pop if name == expected.last || match_acronym?(expected.last, name)
end
false
end
end
def match?(expected)
expected.empty? || expected == [:Object]
end
def match_acronym?(expected, name)
expected = expected.to_s
name = name.to_s
allowed_acronyms.any? { |acronym| expected.gsub(acronym.capitalize, acronym) == name }
end
def to_namespace(path) # rubocop:disable Metrics/AbcSize
components = Pathname(path).each_filename.to_a
# To convert a pathname to a Ruby namespace, we need a starting point
# But RC can be run from any working directory, and can check any path
# We can't assume that the working directory, or any other, is the
# "starting point" to build a namespace.
start = definition_path_hierarchy_roots
start_index = nil
# To find the closest namespace root take the path components, and
# then work through them backwards until we find a candidate. This
# makes sure we work from the actual root in the case of a path like
# /home/user/src/project_name/lib.
components.reverse.each_with_index do |c, i|
if start.include?(c)
start_index = components.size - i
break
end
end
if start_index.nil?
[to_module_name(components.last)]
else
components[start_index..].map { |c| to_module_name(c) }
end
end
def to_module_name(basename)
words = basename.sub(/\..*/, '').split('_')
words.map(&:capitalize).join.to_sym
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/class_and_module_camel_case.rb | lib/rubocop/cop/naming/class_and_module_camel_case.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks for class and module names with
# an underscore in them.
#
# `AllowedNames` config takes an array of permitted names.
# Its default value is `['module_parent']`.
# These names can be full class/module names or part of the name.
# eg. Adding `my_class` to the `AllowedNames` config will allow names like
# `my_class`, `my_class::User`, `App::my_class`, `App::my_class::User`, etc.
#
# @example
# # bad
# class My_Class
# end
# module My_Module
# end
#
# # good
# class MyClass
# end
# module MyModule
# end
# class module_parent::MyModule
# end
class ClassAndModuleCamelCase < Base
MSG = 'Use CamelCase for classes and modules.'
def on_class(node)
return unless node.loc.name.source.include?('_')
allowed = /#{cop_config['AllowedNames'].join('|')}/
name = node.loc.name.source.gsub(allowed, '')
return unless name.include?('_')
add_offense(node.loc.name)
end
alias on_module on_class
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/memoized_instance_variable_name.rb | lib/rubocop/cop/naming/memoized_instance_variable_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks for memoized methods whose instance variable name
# does not match the method name. Applies to both regular methods
# (defined with `def`) and dynamic methods (defined with
# `define_method` or `define_singleton_method`).
#
# This cop can be configured with the EnforcedStyleForLeadingUnderscores
# directive. It can be configured to allow for memoized instance variables
# prefixed with an underscore. Prefixing ivars with an underscore is a
# convention that is used to implicitly indicate that an ivar should not
# be set or referenced outside of the memoization method.
#
# @safety
# This cop relies on the pattern `@instance_var ||= ...`,
# but this is sometimes used for other purposes than memoization
# so this cop is considered unsafe. Also, its autocorrection is unsafe
# because it may conflict with instance variable names already in use.
#
# @example EnforcedStyleForLeadingUnderscores: disallowed (default)
# # bad
# # Method foo is memoized using an instance variable that is
# # not `@foo`. This can cause confusion and bugs.
# def foo
# @something ||= calculate_expensive_thing
# end
#
# def foo
# return @something if defined?(@something)
# @something = calculate_expensive_thing
# end
#
# # good
# def _foo
# @foo ||= calculate_expensive_thing
# end
#
# # good
# def foo
# @foo ||= calculate_expensive_thing
# end
#
# # good
# def foo
# @foo ||= begin
# calculate_expensive_thing
# end
# end
#
# # good
# def foo
# helper_variable = something_we_need_to_calculate_foo
# @foo ||= calculate_expensive_thing(helper_variable)
# end
#
# # good
# define_method(:foo) do
# @foo ||= calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# return @foo if defined?(@foo)
# @foo = calculate_expensive_thing
# end
#
# @example EnforcedStyleForLeadingUnderscores: required
# # bad
# def foo
# @something ||= calculate_expensive_thing
# end
#
# # bad
# def foo
# @foo ||= calculate_expensive_thing
# end
#
# def foo
# return @foo if defined?(@foo)
# @foo = calculate_expensive_thing
# end
#
# # good
# def foo
# @_foo ||= calculate_expensive_thing
# end
#
# # good
# def _foo
# @_foo ||= calculate_expensive_thing
# end
#
# def foo
# return @_foo if defined?(@_foo)
# @_foo = calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# @_foo ||= calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# return @_foo if defined?(@_foo)
# @_foo = calculate_expensive_thing
# end
#
# @example EnforcedStyleForLeadingUnderscores :optional
# # bad
# def foo
# @something ||= calculate_expensive_thing
# end
#
# # good
# def foo
# @foo ||= calculate_expensive_thing
# end
#
# # good
# def foo
# @_foo ||= calculate_expensive_thing
# end
#
# # good
# def _foo
# @_foo ||= calculate_expensive_thing
# end
#
# # good
# def foo
# return @_foo if defined?(@_foo)
# @_foo = calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# @foo ||= calculate_expensive_thing
# end
#
# # good
# define_method(:foo) do
# @_foo ||= calculate_expensive_thing
# end
class MemoizedInstanceVariableName < Base
extend AutoCorrector
include ConfigurableEnforcedStyle
MSG = 'Memoized variable `%<var>s` does not match ' \
'method name `%<method>s`. Use `@%<suggested_var>s` instead.'
UNDERSCORE_REQUIRED = 'Memoized variable `%<var>s` does not start ' \
'with `_`. Use `@%<suggested_var>s` instead.'
DYNAMIC_DEFINE_METHODS = %i[define_method define_singleton_method].to_set.freeze
INITIALIZE_METHODS = %i[initialize initialize_clone initialize_copy initialize_dup].freeze
# @!method method_definition?(node)
def_node_matcher :method_definition?, <<~PATTERN
${
(block (send _ %DYNAMIC_DEFINE_METHODS ({sym str} $_)) ...)
(def $_ ...)
(defs _ $_ ...)
}
PATTERN
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
def on_or_asgn(node)
lhs = node.lhs
return unless lhs.ivasgn_type?
method_node, method_name = find_definition(node)
return unless method_node
body = method_node.body
return unless body == node || body.children.last == node
return if matches?(method_name, lhs)
suggested_var = suggested_var(method_name)
msg = format(
message(lhs.name),
var: lhs.name,
suggested_var: suggested_var,
method: method_name
)
add_offense(lhs, message: msg) do |corrector|
corrector.replace(lhs.loc.name, "@#{suggested_var}")
end
end
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
# @!method defined_memoized?(node, ivar)
def_node_matcher :defined_memoized?, <<~PATTERN
(begin
(if (defined $(ivar %1)) (return $(ivar %1)) nil?)
...
$(ivasgn %1 _))
PATTERN
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def on_defined?(node)
arg = node.first_argument
return false unless arg.ivar_type?
method_node, method_name = find_definition(node)
return false unless method_node
defined_memoized?(method_node.body, arg.name) do |defined_ivar, return_ivar, ivar_assign|
return false if matches?(method_name, ivar_assign)
suggested_var = suggested_var(method_name)
msg = format(
message(arg.name),
var: arg.name,
suggested_var: suggested_var,
method: method_name
)
add_offense(defined_ivar, message: msg) do |corrector|
corrector.replace(defined_ivar, "@#{suggested_var}")
end
add_offense(return_ivar, message: msg) do |corrector|
corrector.replace(return_ivar, "@#{suggested_var}")
end
add_offense(ivar_assign.loc.name, message: msg) do |corrector|
corrector.replace(ivar_assign.loc.name, "@#{suggested_var}")
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
private
def style_parameter_name
'EnforcedStyleForLeadingUnderscores'
end
def find_definition(node)
# Methods can be defined in a `def` or `defs`,
# or dynamically via a `block` node.
node.each_ancestor(:any_def, :block).each do |ancestor|
method_node, method_name = method_definition?(ancestor)
return [method_node, method_name] if method_node
end
nil
end
def matches?(method_name, ivar_assign)
return true if ivar_assign.nil? || INITIALIZE_METHODS.include?(method_name)
method_name = method_name.to_s.delete('!?=')
variable_name = ivar_assign.name.to_s.sub('@', '')
variable_name_candidates(method_name).include?(variable_name)
end
def message(variable)
variable_name = variable.to_s.sub('@', '')
return UNDERSCORE_REQUIRED if style == :required && !variable_name.start_with?('_')
MSG
end
def suggested_var(method_name)
suggestion = method_name.to_s.delete('!?=')
style == :required ? "_#{suggestion}" : suggestion
end
def variable_name_candidates(method_name)
no_underscore = method_name.delete_prefix('_')
with_underscore = "_#{method_name}"
case style
when :required
[with_underscore,
method_name.start_with?('_') ? method_name : nil].compact
when :disallowed
[method_name, no_underscore]
when :optional
[method_name, with_underscore, no_underscore]
else
raise 'Unreachable'
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/variable_number.rb | lib/rubocop/cop/naming/variable_number.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Makes sure that all numbered variables use the
# configured style, snake_case, normalcase, or non_integer,
# for their numbering.
#
# Additionally, `CheckMethodNames` and `CheckSymbols` configuration options
# can be used to specify whether method names and symbols should be checked.
# Both are enabled by default.
#
# @example EnforcedStyle: normalcase (default)
# # bad
# :some_sym_1
# variable_1 = 1
#
# def some_method_1; end
#
# def some_method1(arg_1); end
#
# # good
# :some_sym1
# variable1 = 1
#
# def some_method1; end
#
# def some_method1(arg1); end
#
# @example EnforcedStyle: snake_case
# # bad
# :some_sym1
# variable1 = 1
#
# def some_method1; end
#
# def some_method_1(arg1); end
#
# # good
# :some_sym_1
# variable_1 = 1
#
# def some_method_1; end
#
# def some_method_1(arg_1); end
#
# @example EnforcedStyle: non_integer
# # bad
# :some_sym1
# :some_sym_1
#
# variable1 = 1
# variable_1 = 1
#
# def some_method1; end
#
# def some_method_1; end
#
# def some_methodone(arg1); end
# def some_methodone(arg_1); end
#
# # good
# :some_symone
# :some_sym_one
#
# variableone = 1
# variable_one = 1
#
# def some_methodone; end
#
# def some_method_one; end
#
# def some_methodone(argone); end
# def some_methodone(arg_one); end
#
# # In the following examples, we assume `EnforcedStyle: normalcase` (default).
#
# @example CheckMethodNames: true (default)
# # bad
# def some_method_1; end
#
# @example CheckMethodNames: false
# # good
# def some_method_1; end
#
# @example CheckSymbols: true (default)
# # bad
# :some_sym_1
#
# @example CheckSymbols: false
# # good
# :some_sym_1
#
# @example AllowedIdentifiers: [capture3]
# # good
# expect(Open3).to receive(:capture3)
#
# @example AllowedPatterns: ['_v\d+\z']
# # good
# :some_sym_v1
#
class VariableNumber < Base
include AllowedIdentifiers
include ConfigurableNumbering
include AllowedPattern
MSG = 'Use %<style>s for %<identifier_type>s numbers.'
def valid_name?(node, name, given_style = style)
super || matches_allowed_pattern?(name)
end
def on_arg(node)
@node = node
return if allowed_identifier?(node.name)
check_name(node, node.name, node.loc.name)
end
alias on_lvasgn on_arg
alias on_ivasgn on_arg
alias on_cvasgn on_arg
alias on_gvasgn on_arg
def on_def(node)
@node = node
return if allowed_identifier?(node.method_name)
check_name(node, node.method_name, node.loc.name) if cop_config['CheckMethodNames']
end
alias on_defs on_def
def on_sym(node)
@node = node
return if allowed_identifier?(node.value)
check_name(node, node.value, node) if cop_config['CheckSymbols']
end
private
def message(style)
identifier_type =
case @node.type
when :def, :defs then 'method name'
when :sym then 'symbol'
else 'variable'
end
format(MSG, style: style, identifier_type: identifier_type)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/inclusive_language.rb | lib/rubocop/cop/naming/inclusive_language.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Recommends the use of inclusive language instead of problematic terms.
# The cop can check the following locations for offenses:
#
# - identifiers
# - constants
# - variables
# - strings
# - symbols
# - comments
# - file paths
#
# Each of these locations can be individually enabled/disabled via configuration,
# for example CheckIdentifiers = true/false.
#
# Flagged terms are configurable for the cop. For each flagged term an optional
# Regex can be specified to identify offenses. Suggestions for replacing a flagged term can
# be configured and will be displayed as part of the offense message.
# An AllowedRegex can be specified for a flagged term to exempt allowed uses of the term.
# `WholeWord: true` can be set on a flagged term to indicate the cop should only match when
# a term matches the whole word (partial matches will not be offenses).
#
# The cop supports autocorrection when there is only one suggestion. When there are multiple
# suggestions, the best suggestion cannot be identified and will not be autocorrected.
#
# @example FlaggedTerms: { whitelist: { Suggestions: ['allowlist'] } }
# # Suggest replacing identifier whitelist with allowlist
#
# # bad
# whitelist_users = %w(user1 user1)
#
# # good
# allowlist_users = %w(user1 user2)
#
# @example FlaggedTerms: { master: { Suggestions: ['main', 'primary', 'leader'] } }
# # Suggest replacing master in an instance variable name with main, primary, or leader
#
# # bad
# @master_node = 'node1.example.com'
#
# # good
# @primary_node = 'node1.example.com'
#
# @example FlaggedTerms: { whitelist: { Regex: !ruby/regexp '/white[-_\s]?list' } }
# # Identify problematic terms using a Regexp
#
# # bad
# white_list = %w(user1 user2)
#
# # good
# allow_list = %w(user1 user2)
#
# @example FlaggedTerms: { master: { AllowedRegex: 'master\'?s degree' } }
# # Specify allowed uses of the flagged term as a string or regexp.
#
# # bad
# # They had a masters
#
# # good
# # They had a master's degree
#
# @example FlaggedTerms: { slave: { WholeWord: true } }
# # Specify that only terms that are full matches will be flagged.
#
# # bad
# Slave
#
# # good (won't be flagged despite containing `slave`)
# TeslaVehicle
class InclusiveLanguage < Base
include RangeHelp
extend AutoCorrector
EMPTY_ARRAY = [].freeze
MSG = "Consider replacing '%<term>s'%<suffix>s."
MSG_FOR_FILE_PATH = "Consider replacing '%<term>s' in file path%<suffix>s."
WordLocation = Struct.new(:word, :position)
def initialize(config = nil, options = nil)
super
@flagged_term_hash = {}
@flagged_terms_regex = nil
@allowed_regex = nil
@check_token = preprocess_check_config
preprocess_flagged_terms
end
def on_new_investigation
investigate_filepath if cop_config['CheckFilepaths']
investigate_tokens
end
private
def investigate_tokens
processed_source.tokens.each do |token|
next unless check_token?(token.type)
word_locations = scan_for_words(token.text)
next if word_locations.empty?
add_offenses_for_token(token, word_locations)
end
end
def add_offenses_for_token(token, word_locations)
word_locations.each do |word_location|
word = word_location.word
range = offense_range(token, word)
add_offense(range, message: create_message(word)) do |corrector|
suggestions = find_flagged_term(word)['Suggestions']
if (preferred_term = preferred_sole_term(suggestions))
corrector.replace(range, preferred_term)
end
end
end
end
def check_token?(type)
!!@check_token[type]
end
def preprocess_check_config # rubocop:disable Metrics/AbcSize
{
tIDENTIFIER: cop_config['CheckIdentifiers'],
tCONSTANT: cop_config['CheckConstants'],
tIVAR: cop_config['CheckVariables'],
tCVAR: cop_config['CheckVariables'],
tGVAR: cop_config['CheckVariables'],
tSYMBOL: cop_config['CheckSymbols'],
tSTRING: cop_config['CheckStrings'],
tSTRING_CONTENT: cop_config['CheckStrings'],
tCOMMENT: cop_config['CheckComments']
}.freeze
end
def preprocess_flagged_terms
allowed_strings = []
flagged_term_strings = []
cop_config['FlaggedTerms'].each do |term, term_definition|
next if term_definition.nil?
allowed_strings.concat(process_allowed_regex(term_definition['AllowedRegex']))
regex_string = ensure_regex_string(extract_regexp(term, term_definition))
flagged_term_strings << regex_string
add_to_flagged_term_hash(regex_string, term, term_definition)
end
set_regexes(flagged_term_strings, allowed_strings)
end
def preferred_sole_term(suggestions)
case suggestions
when Array
suggestions.one? && preferred_sole_term(suggestions.first)
when String
suggestions
end
end
def extract_regexp(term, term_definition)
return term_definition['Regex'] if term_definition['Regex']
return /(?:\b|(?<=[\W_]))#{term}(?:\b|(?=[\W_]))/ if term_definition['WholeWord']
term
end
def add_to_flagged_term_hash(regex_string, term, term_definition)
@flagged_term_hash[Regexp.new(regex_string, Regexp::IGNORECASE)] =
term_definition.merge('Term' => term,
'SuggestionString' =>
preprocess_suggestions(term_definition['Suggestions']))
end
def set_regexes(flagged_term_strings, allowed_strings)
@flagged_terms_regex = array_to_ignorecase_regex(flagged_term_strings)
@allowed_regex = array_to_ignorecase_regex(allowed_strings) unless allowed_strings.empty?
end
def process_allowed_regex(allowed)
return EMPTY_ARRAY if allowed.nil?
Array(allowed).map do |allowed_term|
next if allowed_term.is_a?(String) && allowed_term.strip.empty?
ensure_regex_string(allowed_term)
end
end
def ensure_regex_string(regex)
regex.is_a?(Regexp) ? regex.source : regex
end
def array_to_ignorecase_regex(strings)
Regexp.new(strings.join('|'), Regexp::IGNORECASE)
end
def investigate_filepath
word_locations = scan_for_words(processed_source.file_path)
case word_locations.length
when 0
return
when 1
message = create_single_word_message_for_file(word_locations.first.word)
else
words = word_locations.map(&:word)
message = create_multiple_word_message_for_file(words)
end
add_global_offense(message)
end
def create_single_word_message_for_file(word)
create_message(word, MSG_FOR_FILE_PATH)
end
def create_multiple_word_message_for_file(words)
format(MSG_FOR_FILE_PATH, term: words.join("', '"), suffix: ' with other terms')
end
def scan_for_words(input)
masked_input = mask_input(input)
return EMPTY_ARRAY unless masked_input.match?(@flagged_terms_regex)
masked_input.enum_for(:scan, @flagged_terms_regex).map do
match = Regexp.last_match
WordLocation.new(match.to_s, match.offset(0).first)
end
end
def mask_input(str)
safe_str = if str.valid_encoding?
str
else
str.encode('UTF-8', invalid: :replace, undef: :replace)
end
return safe_str if @allowed_regex.nil?
safe_str.gsub(@allowed_regex) { |match| '*' * match.size }
end
def create_message(word, message = MSG)
flagged_term = find_flagged_term(word)
suggestions = flagged_term['SuggestionString']
suggestions = ' with another term' if suggestions.blank?
format(message, term: word, suffix: suggestions)
end
def find_flagged_term(word)
_regexp, flagged_term = @flagged_term_hash.find do |key, _term|
key.match?(word)
end
flagged_term
end
def preprocess_suggestions(suggestions)
return '' if suggestions.nil? ||
(suggestions.is_a?(String) && suggestions.strip.empty?) || suggestions.empty?
format_suggestions(suggestions)
end
def format_suggestions(suggestions)
quoted_suggestions = Array(suggestions).map { |word| "'#{word}'" }
suggestion_str = case quoted_suggestions.size
when 1
quoted_suggestions.first
when 2
quoted_suggestions.join(' or ')
else
last_quoted = quoted_suggestions.pop
quoted_suggestions << "or #{last_quoted}"
quoted_suggestions.join(', ')
end
" with #{suggestion_str}"
end
def offense_range(token, word)
start_position = token.pos.begin_pos + token.pos.source.index(word)
range_between(start_position, start_position + word.length)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/predicate_method.rb | lib/rubocop/cop/naming/predicate_method.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks that predicate methods end with `?` and non-predicate methods do not.
#
# The names of predicate methods (methods that return a boolean value) should end
# in a question mark. Methods that don't return a boolean, shouldn't
# end in a question mark.
#
# The cop assesses a predicate method as one that returns boolean values. Likewise,
# a method that only returns literal values is assessed as non-predicate. Other predicate
# method calls are assumed to return boolean values. The cop does not make an assessment
# if the return type is unknown (non-predicate method calls, variables, etc.).
#
# NOTE: The `initialize` method and operator methods (`def ==`, etc.) are ignored.
#
# By default, the cop runs in `conservative` mode, which allows a method to be named
# with a question mark as long as at least one return value is boolean. In `aggressive`
# mode, methods with a question mark will register an offense if any known non-boolean
# return values are detected.
#
# The cop also has `AllowedMethods` configuration in order to prevent the cop from
# registering an offense from a method name that does not confirm to the naming
# guidelines. By default, `call` is allowed. The cop also has `AllowedPatterns`
# configuration to allow method names by regular expression.
#
# Although returning a call to another predicate method is treated as a boolean value,
# certain method names can be known to not return a boolean, despite ending in a `?`
# (for example, `Numeric#nonzero?` returns `self` or `nil`). These methods can be
# configured using `NonBooleanPredicates`.
#
# The cop can furthermore be configured to allow all bang methods (method names
# ending with `!`), with `AllowBangMethods: true` (default false).
#
# @example Mode: conservative (default)
# # bad
# def foo
# bar == baz
# end
#
# # good
# def foo?
# bar == baz
# end
#
# # bad
# def foo?
# 5
# end
#
# # good
# def foo
# 5
# end
#
# # bad
# def foo
# x == y
# end
#
# # good
# def foo?
# x == y
# end
#
# # bad
# def foo
# !x
# end
#
# # good
# def foo?
# !x
# end
#
# # bad - returns the value of another predicate method
# def foo
# bar?
# end
#
# # good
# def foo?
# bar?
# end
#
# # good - operator method
# def ==(other)
# hash == other.hash
# end
#
# # good - at least one return value is boolean
# def foo?
# return unless bar?
# true
# end
#
# # ok - return type is not known
# def foo?
# bar
# end
#
# # ok - return type is not known
# def foo
# bar?
# end
#
# @example Mode: aggressive
# # bad - the method returns nil in some cases
# def foo?
# return unless bar?
# true
# end
#
# @example AllowedMethods: [call] (default)
# # good
# def call
# foo == bar
# end
#
# @example AllowedPatterns: [\Afoo]
# # good
# def foo?
# 'foo'
# end
#
# @example AllowBangMethods: false (default)
# # bad
# def save!
# true
# end
#
# @example AllowBangMethods: true
# # good
# def save!
# true
# end
#
class PredicateMethod < Base
include AllowedMethods
include AllowedPattern
MSG_PREDICATE = 'Predicate method names should end with `?`.'
MSG_NON_PREDICATE = 'Non-predicate method names should not end with `?`.'
def on_def(node)
return if allowed?(node)
return_values = return_values(node.body)
return if acceptable?(return_values)
if node.predicate_method? && potential_non_predicate?(return_values)
add_offense(node.loc.name, message: MSG_NON_PREDICATE)
elsif !node.predicate_method? && all_return_values_boolean?(return_values)
add_offense(node.loc.name, message: MSG_PREDICATE)
end
end
alias on_defs on_def
private
def allowed?(node)
node.method?(:initialize) ||
allowed_method?(node.method_name) ||
matches_allowed_pattern?(node.method_name) ||
allowed_bang_method?(node) ||
node.operator_method? ||
node.body.nil?
end
def acceptable?(return_values)
# In `conservative` mode, if the method returns `super`, `zsuper`, or a
# non-comparison method call, the method name is acceptable.
return false unless conservative?
return_values.any? do |value|
value.type?(:super, :zsuper) || unknown_method_call?(value)
end
end
def unknown_method_call?(value)
return false unless value.call_type?
!method_returning_boolean?(value)
end
def return_values(node)
# Collect all the (implicit and explicit) return values of a node
return_values = Set.new(node.begin_type? ? [] : [extract_return_value(node)])
node.each_descendant(:return) do |return_node|
return_values << extract_return_value(return_node)
end
return_values << last_value(node)
process_return_values(return_values)
end
def all_return_values_boolean?(return_values)
values = return_values.reject { |value| value.type?(:super, :zsuper) }
return false if values.empty?
values.all? { |value| boolean_return?(value) }
end
def boolean_return?(value)
return true if value.boolean_type?
method_returning_boolean?(value)
end
def method_returning_boolean?(value)
return false unless value.call_type?
return false if wayward_predicate?(value.method_name)
value.comparison_method? || value.predicate_method? || value.negation_method?
end
def potential_non_predicate?(return_values)
# Assumes a method to be non-predicate if all return values are non-boolean literals.
#
# In `Mode: conservative`, if any of the return values is a boolean,
# the method name is acceptable.
# In `Mode: aggressive`, all return values must be booleans for a predicate
# method, or else an offense will be registered.
return false if conservative? && return_values.any? { |value| boolean_return?(value) }
return_values.any? do |value|
value.literal? && !value.boolean_type?
end
end
def extract_return_value(node)
return node unless node.return_type?
# `return` without a value is a `nil` return.
return s(:nil) if node.arguments.empty?
# When there's a multiple return, it cannot be a predicate
# so just return an `array` sexp for simplicity.
return s(:array) unless node.arguments.one?
node.first_argument
end
def last_value(node)
value = node.begin_type? ? node.children.last || s(:nil) : node
value.return_type? ? extract_return_value(value) : value
end
def process_return_values(return_values)
return_values.flat_map do |value|
if value.conditional?
process_return_values(extract_conditional_branches(value))
elsif and_or?(value)
process_return_values(extract_and_or_clauses(value))
else
value
end
end
end
def and_or?(node)
node.type?(:and, :or)
end
def extract_and_or_clauses(node)
# Recursively traverse an `and` or `or` node to collect all clauses within
return node unless and_or?(node)
[extract_and_or_clauses(node.lhs), extract_and_or_clauses(node.rhs)].flatten
end
def extract_conditional_branches(node)
return node unless node.conditional?
if node.type?(:while, :until)
# If there is no body, act as implicit `nil`.
node.body ? [last_value(node.body)] : [s(:nil)]
else
# Branches with no value act as an implicit `nil`.
branches = node.branches.map { |branch| branch ? last_value(branch) : s(:nil) }
# Missing else branches also act as an implicit `nil`.
branches.push(s(:nil)) unless node.else_branch
branches
end
end
def conservative?
cop_config.fetch('Mode', :conservative).to_sym == :conservative
end
def allowed_bang_method?(node)
return false unless allow_bang_methods?
node.bang_method?
end
def allow_bang_methods?
cop_config.fetch('AllowBangMethods', false)
end
# If a method ending in `?` is known to not return a boolean value,
# (for example, `Numeric#nonzero?`) it should be treated as a non-boolean
# value, despite the method naming.
def wayward_predicate?(name)
wayward_predicates.include?(name.to_s)
end
def wayward_predicates
Array(cop_config.fetch('WaywardPredicates', []))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/predicate_prefix.rb | lib/rubocop/cop/naming/predicate_prefix.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks that predicate method names end with a question mark and
# do not start with a forbidden prefix.
#
# A method is determined to be a predicate method if its name starts with
# one of the prefixes listed in the `NamePrefix` configuration. The list
# defaults to `is_`, `has_`, and `have_` but may be overridden.
#
# Predicate methods must end with a question mark.
#
# When `ForbiddenPrefixes` is also set (as it is by default), predicate
# methods which begin with a forbidden prefix are not allowed, even if
# they end with a `?`. These methods should be changed to remove the
# prefix.
#
# When `UseSorbetSigs` set to true (optional), the cop will only report
# offenses if the method has a Sorbet `sig` with a return type of
# `T::Boolean`. Dynamic methods are not supported with this configuration.
#
# @example NamePrefix: ['is_', 'has_', 'have_'] (default)
# # bad
# def is_even(value)
# end
#
# # When ForbiddenPrefixes: ['is_', 'has_', 'have_'] (default)
# # good
# def even?(value)
# end
#
# # When ForbiddenPrefixes: []
# # good
# def is_even?(value)
# end
#
# @example NamePrefix: ['seems_to_be_']
# # bad
# def seems_to_be_even(value)
# end
#
# # When ForbiddenPrefixes: ['seems_to_be_']
# # good
# def even?(value)
# end
#
# # When ForbiddenPrefixes: []
# # good
# def seems_to_be_even?(value)
# end
#
# @example AllowedMethods: ['is_a?'] (default)
# # Despite starting with the `is_` prefix, this method is allowed
# # good
# def is_a?(value)
# end
#
# @example AllowedMethods: ['is_even?']
# # good
# def is_even?(value)
# end
#
# @example UseSorbetSigs: false (default)
# # bad
# sig { returns(String) }
# def is_this_thing_on
# "yes"
# end
#
# # good - Sorbet signature is not evaluated
# sig { returns(String) }
# def is_this_thing_on?
# "yes"
# end
#
# @example UseSorbetSigs: true
# # bad
# sig { returns(T::Boolean) }
# def odd(value)
# end
#
# # good
# sig { returns(T::Boolean) }
# def odd?(value)
# end
#
# @example MethodDefinitionMacros: ['define_method', 'define_singleton_method'] (default)
# # bad
# define_method(:is_even) { |value| }
#
# # good
# define_method(:even?) { |value| }
#
# @example MethodDefinitionMacros: ['def_node_matcher']
# # bad
# def_node_matcher(:is_even) { |value| }
#
# # good
# def_node_matcher(:even?) { |value| }
#
class PredicatePrefix < Base
include AllowedMethods
# @!method dynamic_method_define(node)
def_node_matcher :dynamic_method_define, <<~PATTERN
(send nil? #method_definition_macro?
(sym $_)
...)
PATTERN
def on_send(node)
dynamic_method_define(node) do |method_name|
predicate_prefixes.each do |prefix|
next if allowed_method_name?(method_name.to_s, prefix)
add_offense(
node.first_argument,
message: message(method_name, expected_name(method_name.to_s, prefix))
)
end
end
end
def on_def(node)
predicate_prefixes.each do |prefix|
method_name = node.method_name.to_s
next if allowed_method_name?(method_name, prefix)
next if use_sorbet_sigs? && !sorbet_sig?(node, return_type: 'T::Boolean')
add_offense(
node.loc.name,
message: message(method_name, expected_name(method_name, prefix))
)
end
end
alias on_defs on_def
def validate_config
forbidden_prefixes.each do |forbidden_prefix|
next if predicate_prefixes.include?(forbidden_prefix)
raise ValidationError, <<~MSG.chomp
The `Naming/PredicatePrefix` cop is misconfigured. Prefix #{forbidden_prefix} must be included in NamePrefix because it is included in ForbiddenPrefixes.
MSG
end
end
private
# @!method sorbet_return_type(node)
def_node_matcher :sorbet_return_type, <<~PATTERN
(block (send nil? :sig) args (send _ :returns $_type))
PATTERN
def sorbet_sig?(node, return_type: nil)
return false unless (type = sorbet_return_type(node.left_sibling))
type.source == return_type
end
def allowed_method_name?(method_name, prefix)
!(method_name.start_with?(prefix) && # cheap check to avoid allocating Regexp
method_name.match?(/^#{prefix}[^0-9]/)) ||
method_name == expected_name(method_name, prefix) ||
method_name.end_with?('=') ||
allowed_method?(method_name)
end
def expected_name(method_name, prefix)
new_name = if forbidden_prefixes.include?(prefix)
method_name.sub(prefix, '')
else
method_name.dup
end
new_name << '?' unless method_name.end_with?('?')
new_name
end
def message(method_name, new_name)
"Rename `#{method_name}` to `#{new_name}`."
end
def forbidden_prefixes
cop_config['ForbiddenPrefixes']
end
def predicate_prefixes
cop_config['NamePrefix']
end
def use_sorbet_sigs?
cop_config['UseSorbetSigs']
end
def method_definition_macro?(macro_name)
cop_config['MethodDefinitionMacros'].include?(macro_name.to_s)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/heredoc_delimiter_case.rb | lib/rubocop/cop/naming/heredoc_delimiter_case.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks that your heredocs are using the configured case.
# By default it is configured to enforce uppercase heredocs.
#
# @example EnforcedStyle: uppercase (default)
# # bad
# <<-sql
# SELECT * FROM foo
# sql
#
# # good
# <<-SQL
# SELECT * FROM foo
# SQL
#
# @example EnforcedStyle: lowercase
# # bad
# <<-SQL
# SELECT * FROM foo
# SQL
#
# # good
# <<-sql
# SELECT * FROM foo
# sql
class HeredocDelimiterCase < Base
include Heredoc
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Use %<style>s heredoc delimiters.'
def on_heredoc(node)
return if correct_case_delimiters?(node)
add_offense(node.loc.heredoc_end) do |corrector|
expr = node.source_range
corrector.replace(expr, correct_delimiters(expr.source))
corrector.replace(node.loc.heredoc_end, correct_delimiters(delimiter_string(expr)))
end
end
private
def message(_node)
format(MSG, style: style)
end
def correct_case_delimiters?(node)
delimiter_string(node) == correct_delimiters(delimiter_string(node))
end
def correct_delimiters(source)
if style == :uppercase
source.upcase
else
source.downcase
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/block_forwarding.rb | lib/rubocop/cop/naming/block_forwarding.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# In Ruby 3.1, anonymous block forwarding has been added.
#
# This cop identifies places where `do_something(&block)` can be replaced
# by `do_something(&)`.
#
# It also supports the opposite style by alternative `explicit` option.
# You can specify the block variable name for autocorrection with `BlockForwardingName`.
# The default variable name is `block`. If the name is already in use, it will not be
# autocorrected.
#
# [NOTE]
# ====
# Because of a bug in Ruby 3.3.0, when a block is referenced inside of another block,
# no offense will be registered until Ruby 3.4:
#
# [source,ruby]
# ----
# def foo(&block)
# # Using an anonymous block would be a syntax error on Ruby 3.3.0
# block_method { bar(&block) }
# end
# ----
# ====
#
# @example EnforcedStyle: anonymous (default)
#
# # bad
# def foo(&block)
# bar(&block)
# end
#
# # good
# def foo(&)
# bar(&)
# end
#
# @example EnforcedStyle: explicit
#
# # bad
# def foo(&)
# bar(&)
# end
#
# # good
# def foo(&block)
# bar(&block)
# end
#
class BlockForwarding < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 3.1
MSG = 'Use %<style>s block forwarding.'
def self.autocorrect_incompatible_with
[Lint::AmbiguousOperator, Style::ArgumentsForwarding, Style::ExplicitBlockArgument]
end
def on_def(node)
return if node.arguments.empty?
last_argument = node.last_argument
return if expected_block_forwarding_style?(node, last_argument)
forwarded_args = node.each_descendant(:block_pass).with_object([]) do |block_pass, result|
return nil if invalidates_syntax?(block_pass)
next unless block_argument_name_matched?(block_pass, last_argument)
result << block_pass
end
forwarded_args.each do |forwarded_arg|
register_offense(forwarded_arg, node)
end
register_offense(last_argument, node)
end
alias on_defs on_def
private
def expected_block_forwarding_style?(node, last_argument)
if style == :anonymous
!explicit_block_argument?(last_argument) ||
use_kwarg_in_method_definition?(node) ||
use_block_argument_as_local_variable?(node, last_argument.source[1..])
else
!anonymous_block_argument?(last_argument)
end
end
def block_argument_name_matched?(block_pass_node, last_argument)
return false if block_pass_node.children.first&.sym_type?
last_argument.source == block_pass_node.source
end
# Ruby 3.3.0 had a bug where accessing an anonymous block argument inside of a block
# was a syntax error in unambiguous cases: https://bugs.ruby-lang.org/issues/20090
# We disallow this also for earlier Ruby versions so that code is forwards compatible.
def invalidates_syntax?(block_pass_node)
target_ruby_version <= 3.3 && block_pass_node.each_ancestor(:any_block).any?
end
def use_kwarg_in_method_definition?(node)
node.arguments.each_descendant(:kwarg, :kwoptarg).any?
end
def anonymous_block_argument?(node)
node.blockarg_type? && node.name.nil?
end
def explicit_block_argument?(node)
node.blockarg_type? && !node.name.nil?
end
def register_offense(block_argument, node)
add_offense(block_argument, message: format(MSG, style: style)) do |corrector|
if style == :anonymous
corrector.replace(block_argument, '&')
arguments = block_argument.parent
add_parentheses(arguments, corrector) unless arguments.parenthesized_call?
else
unless use_block_argument_as_local_variable?(node, block_forwarding_name)
corrector.replace(block_argument, "&#{block_forwarding_name}")
end
end
end
end
def use_block_argument_as_local_variable?(node, last_argument)
return false if node.body.nil?
node.body.each_node(:lvar, :lvasgn).any? do |lvar|
!lvar.parent.block_pass_type? && lvar.node_parts[0].to_s == last_argument
end
end
def block_forwarding_name
cop_config.fetch('BlockForwardingName', 'block')
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/binary_operator_parameter_name.rb | lib/rubocop/cop/naming/binary_operator_parameter_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Makes sure that certain binary operator methods have their
# sole parameter named `other`.
#
# @example
#
# # bad
# def +(amount); end
#
# # good
# def +(other); end
class BinaryOperatorParameterName < Base
extend AutoCorrector
MSG = 'When defining the `%<opr>s` operator, name its argument `other`.'
OP_LIKE_METHODS = %i[eql? equal?].freeze
EXCLUDED = %i[+@ -@ [] []= << === ` =~].freeze
# @!method op_method_candidate?(node)
def_node_matcher :op_method_candidate?, <<~PATTERN
(def [#op_method? $_] (args $(arg [!:other !:_other])) _)
PATTERN
def on_def(node)
op_method_candidate?(node) do |name, arg|
add_offense(arg, message: format(MSG, opr: name)) do |corrector|
corrector.replace(arg, 'other')
node.each_descendant(:lvar, :lvasgn) do |lvar|
lvar_location = lvar.loc.name
next unless lvar_location.source == arg.source
corrector.replace(lvar_location, 'other')
end
end
end
end
private
def op_method?(name)
return false if EXCLUDED.include?(name)
!/\A[[:word:]]/.match?(name) || OP_LIKE_METHODS.include?(name)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/naming/constant_name.rb | lib/rubocop/cop/naming/constant_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Naming
# Checks whether constant names are written using
# SCREAMING_SNAKE_CASE.
#
# To avoid false positives, it ignores cases in which we cannot know
# for certain the type of value that would be assigned to a constant.
#
# @example
# # bad
# InchInCm = 2.54
# INCHinCM = 2.54
# Inch_In_Cm = 2.54
#
# # good
# INCH_IN_CM = 2.54
class ConstantName < Base
MSG = 'Use SCREAMING_SNAKE_CASE for constants.'
# Use POSIX character classes, so we allow accented characters rather
# than just standard ASCII characters
SNAKE_CASE = /^[[:digit:][:upper:]_]+$/.freeze
# @!method class_or_struct_return_method?(node)
def_node_matcher :class_or_struct_return_method?, <<~PATTERN
(send
(const _ {:Class :Struct}) :new
...)
PATTERN
def on_casgn(node)
value = if node.parent&.or_asgn_type?
node.parent.expression
else
node.expression
end
# We cannot know the result of method calls like
# NewClass = something_that_returns_a_class
# It's also ok to assign a class constant another class constant,
# `Class.new(...)` or `Struct.new(...)`
# SomeClass = SomeOtherClass
# SomeClass = Class.new(...)
# SomeClass = Struct.new(...)
return if allowed_assignment?(value)
return if SNAKE_CASE.match?(node.name)
add_offense(node.loc.name)
end
private
def allowed_assignment?(value)
(value && %i[block const casgn].include?(value.type)) ||
allowed_method_call_on_rhs?(value) ||
class_or_struct_return_method?(value) ||
allowed_conditional_expression_on_rhs?(value)
end
def allowed_method_call_on_rhs?(node)
node&.send_type? && (node.receiver.nil? || !literal_receiver?(node))
end
# @!method literal_receiver?(node)
def_node_matcher :literal_receiver?, <<~PATTERN
{(send literal? ...)
(send (begin literal?) ...)}
PATTERN
def allowed_conditional_expression_on_rhs?(node)
node&.if_type? && contains_constant?(node)
end
def contains_constant?(node)
node.branches.compact.any?(&:const_type?)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/variable_force/reference.rb | lib/rubocop/cop/variable_force/reference.rb | # frozen_string_literal: true
module RuboCop
module Cop
class VariableForce
# This class represents each reference of a variable.
class Reference
include Branchable
VARIABLE_REFERENCE_TYPES = (
[VARIABLE_REFERENCE_TYPE] + OPERATOR_ASSIGNMENT_TYPES + [ZERO_ARITY_SUPER_TYPE, SEND_TYPE]
).freeze
attr_reader :node, :scope
def initialize(node, scope)
unless VARIABLE_REFERENCE_TYPES.include?(node.type)
raise ArgumentError,
"Node type must be any of #{VARIABLE_REFERENCE_TYPES}, " \
"passed #{node.type}"
end
@node = node
@scope = scope
end
# There's an implicit variable reference by the zero-arity `super`:
#
# def some_method(foo)
# super
# end
#
# Another case is `binding`:
#
# def some_method(foo)
# do_something(binding)
# end
#
# In these cases, the variable `foo` is not explicitly referenced,
# but it can be considered used implicitly by the `super` or `binding`.
def explicit?
![ZERO_ARITY_SUPER_TYPE, SEND_TYPE].include?(@node.type)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/variable_force/branchable.rb | lib/rubocop/cop/variable_force/branchable.rb | # frozen_string_literal: true
module RuboCop
module Cop
class VariableForce
# Mix-in module for classes which own a node and need branch information
# of the node. The user classes must implement #node and #scope.
module Branchable
def branch
return @branch if instance_variable_defined?(:@branch)
@branch = Branch.of(node, scope: scope)
end
def run_exclusively_with?(other)
return false if !branch || !other.branch
branch.exclusive_with?(other.branch)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/variable_force/assignment.rb | lib/rubocop/cop/variable_force/assignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
class VariableForce
# This class represents each assignment of a variable.
class Assignment
include Branchable
MULTIPLE_LEFT_HAND_SIDE_TYPE = :mlhs
attr_reader :node, :variable, :referenced, :references, :reassigned
alias referenced? referenced
alias reassigned? reassigned
def initialize(node, variable)
unless VARIABLE_ASSIGNMENT_TYPES.include?(node.type)
raise ArgumentError,
"Node type must be any of #{VARIABLE_ASSIGNMENT_TYPES}, " \
"passed #{node.type}"
end
@node = node
@variable = variable
@referenced = false
@references = []
@reassigned = false
end
def name
@node.children.first
end
def scope
@variable.scope
end
def reference!(node)
@references << node
@referenced = true
end
def reassigned!
return if referenced?
@reassigned = true
end
def used?
(!reassigned? && @variable.captured_by_block?) || @referenced
end
def regexp_named_capture?
@node.type == REGEXP_NAMED_CAPTURE_TYPE
end
def exception_assignment?
node.parent&.resbody_type? && node.parent.exception_variable == node
end
def operator_assignment?
return false unless meta_assignment_node
OPERATOR_ASSIGNMENT_TYPES.include?(meta_assignment_node.type)
end
def multiple_assignment?
return false unless meta_assignment_node
meta_assignment_node.type == MULTIPLE_ASSIGNMENT_TYPE
end
def rest_assignment?
return false unless meta_assignment_node
meta_assignment_node.type == REST_ASSIGNMENT_TYPE
end
def for_assignment?
return false unless meta_assignment_node
meta_assignment_node.for_type?
end
def operator
assignment_node = meta_assignment_node || @node
assignment_node.loc.operator.source
end
def meta_assignment_node
unless instance_variable_defined?(:@meta_assignment_node)
@meta_assignment_node = operator_assignment_node ||
multiple_assignment_node ||
rest_assignment_node ||
for_assignment_node
end
@meta_assignment_node
end
private
def operator_assignment_node
return nil unless node.parent
return nil unless OPERATOR_ASSIGNMENT_TYPES.include?(node.parent.type)
return nil unless node.sibling_index.zero?
node.parent
end
def multiple_assignment_node
return nil unless (candidate_mlhs_node = node.parent)
# In `(foo, bar), *baz`, the splat node must be traversed as well.
candidate_mlhs_node = candidate_mlhs_node.parent if candidate_mlhs_node.splat_type?
return nil unless candidate_mlhs_node.mlhs_type?
return nil unless (grandparent_node = node.parent.parent)
if (node = find_multiple_assignment_node(grandparent_node))
return node
end
return nil unless grandparent_node.type == MULTIPLE_ASSIGNMENT_TYPE
grandparent_node
end
def rest_assignment_node
return nil unless node.parent
return nil unless node.parent.type == REST_ASSIGNMENT_TYPE
node.parent
end
def for_assignment_node
return unless (parent_node = node.parent)
return parent_node if parent_node.for_type?
grandparent_node = parent_node.parent
return grandparent_node if parent_node.mlhs_type? && grandparent_node&.for_type?
nil
end
def find_multiple_assignment_node(grandparent_node)
return unless grandparent_node.type == MULTIPLE_LEFT_HAND_SIDE_TYPE
parent = grandparent_node.parent
return parent if parent.type == MULTIPLE_ASSIGNMENT_TYPE
find_multiple_assignment_node(parent)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/variable_force/scope.rb | lib/rubocop/cop/variable_force/scope.rb | # frozen_string_literal: true
module RuboCop
module Cop
class VariableForce
# A Scope represents a context of local variable visibility.
# This is a place where local variables belong to.
# A scope instance holds a scope node and variable entries.
class Scope
OUTER_SCOPE_CHILD_INDICES = {
defs: 0..0,
module: 0..0,
class: 0..1,
sclass: 0..0,
block: 0..0
}.freeze
attr_reader :node, :variables, :naked_top_level
alias naked_top_level? naked_top_level
def initialize(node)
unless SCOPE_TYPES.include?(node.type)
# Accept any node type for top level scope
if node.parent
raise ArgumentError, "Node type must be any of #{SCOPE_TYPES}, passed #{node.type}"
end
@naked_top_level = true
end
@node = node
@variables = {}
end
def ==(other)
@node.equal?(other.node)
end
def name
@node.method_name
end
def body_node
if naked_top_level?
node
else
child_index = case node.type
when :module, :sclass then 1
when :def, :class, :block, :numblock, :itblock then 2
when :defs then 3
end
node.children[child_index]
end
end
def include?(target_node)
!belong_to_outer_scope?(target_node) && !belong_to_inner_scope?(target_node)
end
def each_node(&block)
return to_enum(__method__) unless block
yield node if naked_top_level?
scan_node(node, &block)
end
private
def scan_node(node, &block)
node.each_child_node do |child_node|
next unless include?(child_node)
yield child_node
scan_node(child_node, &block)
end
end
def belong_to_outer_scope?(target_node)
return true if !naked_top_level? && target_node.equal?(node)
return true if ancestor_node?(target_node)
return false unless target_node.parent.equal?(node)
indices = OUTER_SCOPE_CHILD_INDICES[target_node.parent.type]
return false unless indices
indices.include?(target_node.sibling_index)
end
def belong_to_inner_scope?(target_node)
return false if !target_node.parent || target_node.parent.equal?(node)
return false unless SCOPE_TYPES.include?(target_node.parent.type)
indices = OUTER_SCOPE_CHILD_INDICES[target_node.parent.type]
return true unless indices
!indices.include?(target_node.sibling_index)
end
def ancestor_node?(target_node)
node.each_ancestor.any? { |ancestor_node| ancestor_node.equal?(target_node) }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/variable_force/variable.rb | lib/rubocop/cop/variable_force/variable.rb | # frozen_string_literal: true
module RuboCop
module Cop
class VariableForce
# A Variable represents existence of a local variable.
# This holds a variable declaration node and some states of the variable.
class Variable
VARIABLE_DECLARATION_TYPES = (VARIABLE_ASSIGNMENT_TYPES + ARGUMENT_DECLARATION_TYPES).freeze
attr_reader :name, :declaration_node, :scope, :assignments, :references, :captured_by_block
alias captured_by_block? captured_by_block
def initialize(name, declaration_node, scope)
unless VARIABLE_DECLARATION_TYPES.include?(declaration_node.type)
raise ArgumentError,
"Node type must be any of #{VARIABLE_DECLARATION_TYPES}, " \
"passed #{declaration_node.type}"
end
@name = name.to_sym
@declaration_node = declaration_node
@scope = scope
@assignments = []
@references = []
@captured_by_block = false
end
def assign(node)
assignment = Assignment.new(node, self)
mark_last_as_reassigned!(assignment)
@assignments << assignment
end
def mark_last_as_reassigned!(assignment)
return if captured_by_block?
return unless assignment.branch == @assignments.last&.branch
@assignments.last&.reassigned!
end
def referenced?
!@references.empty?
end
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def reference!(node)
reference = Reference.new(node, @scope)
@references << reference
consumed_branches = nil
@assignments.reverse_each do |assignment|
next if consumed_branches&.include?(assignment.branch)
assignment.reference!(node) unless assignment.run_exclusively_with?(reference)
# Modifier if/unless conditions are special. Assignments made in
# them do not put the assigned variable in scope to the left of the
# if/unless keyword. A preceding assignment is needed to put the
# variable in scope. For this reason we skip to the next assignment
# here.
next if in_modifier_conditional?(assignment)
break if !assignment.branch || assignment.branch == reference.branch
unless assignment.branch.may_run_incompletely?
(consumed_branches ||= Set.new) << assignment.branch
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def in_modifier_conditional?(assignment)
parent = assignment.node.parent
parent = parent.parent if parent&.begin_type?
return false if parent.nil?
parent.basic_conditional? && parent.modifier_form?
end
def capture_with_block!
@captured_by_block = true
end
# This is a convenient way to check whether the variable is used
# in its entire variable lifetime.
# For more precise usage check, refer Assignment#used?.
#
# Once the variable is captured by a block, we have no idea
# when, where, and how many times the block would be invoked.
# This means we cannot track the usage of the variable.
# So we consider it's used to suppress false positive offenses.
def used?
@captured_by_block || referenced?
end
def should_be_unused?
name.to_s.start_with?('_')
end
def argument?
ARGUMENT_DECLARATION_TYPES.include?(@declaration_node.type)
end
def method_argument?
argument? && @scope.node.any_def_type?
end
def block_argument?
argument? && @scope.node.block_type?
end
def keyword_argument?
%i[kwarg kwoptarg].include?(@declaration_node.type)
end
def explicit_block_local_variable?
@declaration_node.shadowarg_type?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/variable_force/variable_table.rb | lib/rubocop/cop/variable_force/variable_table.rb | # frozen_string_literal: true
module RuboCop
module Cop
class VariableForce
# A VariableTable manages the lifetime of all scopes and local variables
# in a program.
# This holds scopes as stack structure, provides a way to add local
# variables to current scope, and find local variables by considering
# variable visibility of the current scope.
class VariableTable
def initialize(hook_receiver = nil)
@hook_receiver = hook_receiver
end
def invoke_hook(hook_name, *args)
@hook_receiver&.send(hook_name, *args)
end
def scope_stack
@scope_stack ||= []
end
def push_scope(scope_node)
scope = Scope.new(scope_node)
invoke_hook(:before_entering_scope, scope)
scope_stack.push(scope)
invoke_hook(:after_entering_scope, scope)
scope
end
def pop_scope
scope = current_scope
invoke_hook(:before_leaving_scope, scope)
scope_stack.pop
invoke_hook(:after_leaving_scope, scope)
scope
end
def current_scope
scope_stack.last
end
def current_scope_level
scope_stack.count
end
def declare_variable(name, node)
variable = Variable.new(name, node, current_scope)
invoke_hook(:before_declaring_variable, variable)
current_scope.variables[variable.name] = variable
invoke_hook(:after_declaring_variable, variable)
variable
end
def assign_to_variable(name, node)
variable = find_variable(name)
unless variable
raise "Assigning to undeclared local variable \"#{name}\" " \
"at #{node.source_range}, #{node.inspect}"
end
mark_variable_as_captured_by_block_if_so(variable)
variable.assign(node)
end
def reference_variable(name, node)
variable = find_variable(name)
# In this code:
#
# foo = 1 unless foo
#
# (if
# (lvar :foo) nil
# (lvasgn :foo
# (int 1)))
#
# Parser knows whether the foo is a variable or method invocation.
# This means that if a :lvar node is shown in AST, the variable is
# assumed to be already declared, even if we haven't seen any :lvasgn
# or :arg node before the :lvar node.
#
# We don't invoke #declare_variable here otherwise
# Variable#declaration_node will be :lvar node, that is actually not.
# So just skip.
return unless variable
mark_variable_as_captured_by_block_if_so(variable)
variable.reference!(node)
end
def find_variable(name)
name = name.to_sym
scope_stack.reverse_each do |scope|
variable = scope.variables[name]
return variable if variable
# Only block scope allows referencing outer scope variables.
node = scope.node
return nil unless node.any_block_type?
end
nil
end
def variable_exist?(name)
find_variable(name)
end
def accessible_variables
scope_stack.reverse_each.with_object([]) do |scope, variables|
variables.concat(scope.variables.values)
break variables unless scope.node.any_block_type?
end
end
private
def mark_variable_as_captured_by_block_if_so(variable)
return unless current_scope.node.any_block_type?
return if variable.scope == current_scope
variable.capture_with_block!
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/variable_force/branch.rb | lib/rubocop/cop/variable_force/branch.rb | # frozen_string_literal: true
module RuboCop
module Cop
class VariableForce
# Namespace for branch classes for each control structure.
module Branch
def self.of(target_node, scope: nil)
([target_node] + target_node.ancestors).each do |node|
return nil unless node.parent
return nil unless scope.include?(node)
klass = CLASSES_BY_TYPE[node.parent.type]
next unless klass
branch = klass.new(node, scope)
return branch if branch.branched?
end
nil
end
# Abstract base class for branch classes.
# A branch represents a conditional branch in a scope.
#
# @example
# def some_scope
# do_something # no branch
#
# if foo
# do_something # branch A
# do_something # branch A
# else
# do_something # branch B
# if bar
# do_something # branch C (whose parent is branch B)
# end
# end
#
# do_something # no branch
# end
Base = Struct.new(:child_node, :scope) do
def self.classes
@classes ||= []
end
def self.inherited(subclass)
super
classes << subclass
end
def self.type
name.split('::').last.gsub(/(.)([A-Z])/, '\1_\2').downcase.to_sym
end
def self.define_predicate(name, child_index: nil)
define_method(name) do
target_node = control_node.children[child_index]
# We don't use Kernel#Array here
# because it invokes Node#to_a rather than wrapping with an array.
if target_node.is_a?(Array)
target_node.any? { |node| node.equal?(child_node) }
else
target_node.equal?(child_node)
end
end
end
def control_node
child_node.parent
end
def parent
return @parent if instance_variable_defined?(:@parent)
@parent = Branch.of(control_node, scope: scope)
end
def each_ancestor(include_self: false, &block)
return to_enum(__method__, include_self: include_self) unless block
yield self if include_self
scan_ancestors(&block)
self
end
def branched?
!always_run?
end
def always_run?
raise NotImplementedError
end
def may_jump_to_other_branch?
false
end
def may_run_incompletely?
false
end
def exclusive_with?(other)
return false unless other
return false if may_jump_to_other_branch?
other.each_ancestor(include_self: true) do |other_ancestor|
if control_node.equal?(other_ancestor.control_node)
return !child_node.equal?(other_ancestor.child_node)
end
end
if parent
parent.exclusive_with?(other)
else
false
end
end
def ==(other)
return false unless other
control_node.equal?(other.control_node) && child_node.equal?(other.child_node)
end
alias_method :eql?, :==
def hash
[control_node.object_id, control_node.object_id].hash
end
private
def scan_ancestors
branch = self
while (branch = branch.parent)
yield branch
end
end
end
# Mix-in module for simple conditional control structures.
module SimpleConditional
def conditional_clause?
raise NotImplementedError
end
def always_run?
conditional_clause?
end
end
# if conditional_clause
# truthy_body
# else
# falsey_body
# end
#
# unless conditional_clause
# falsey_body
# else
# truthy_body
# end
class If < Base
include SimpleConditional
define_predicate :conditional_clause?, child_index: 0
define_predicate :truthy_body?, child_index: 1
define_predicate :falsey_body?, child_index: 2
end
# while conditional_clause
# loop_body
# end
class While < Base
include SimpleConditional
define_predicate :conditional_clause?, child_index: 0
define_predicate :loop_body?, child_index: 1
end
# until conditional_clause
# loop_body
# end
class Until < Base
include SimpleConditional
define_predicate :conditional_clause?, child_index: 0
define_predicate :loop_body?, child_index: 1
end
# begin
# loop_body
# end while conditional_clause
class WhilePost < Base
include SimpleConditional
define_predicate :conditional_clause?, child_index: 0
define_predicate :loop_body?, child_index: 1
end
# begin
# loop_body
# end until conditional_clause
class UntilPost < Base
include SimpleConditional
define_predicate :conditional_clause?, child_index: 0
define_predicate :loop_body?, child_index: 1
end
# case target
# when /pattern/ # when_clause
# else
# else_body
# end
class Case < Base
define_predicate :target?, child_index: 0
define_predicate :when_clause?, child_index: 1..-2
define_predicate :else_body?, child_index: -1
def always_run?
target?
end
end
# case target
# in pattern # in_pattern
# else
# else_body
# end
class CaseMatch < Base
define_predicate :target?, child_index: 0
define_predicate :in_pattern?, child_index: 1..-2
define_predicate :else_body?, child_index: -1
def always_run?
target?
end
end
# for element in collection
# loop_body
# end
class For < Base
define_predicate :element?, child_index: 0
define_predicate :collection?, child_index: 1
define_predicate :loop_body?, child_index: 2
def always_run?
element? || collection?
end
end
# Mix-in module for logical operator control structures.
module LogicalOperator
def always_run?
left_body?
end
end
# left_body && right_body
class And < Base
include LogicalOperator
define_predicate :left_body?, child_index: 0
define_predicate :right_body?, child_index: 1
end
# left_body || right_body
class Or < Base
include LogicalOperator
define_predicate :left_body?, child_index: 0
define_predicate :right_body?, child_index: 1
end
# Mix-in module for exception handling control structures.
module ExceptionHandler
def may_jump_to_other_branch?
main_body?
end
def may_run_incompletely?
main_body?
end
end
# begin
# main_body
# rescue StandardError => error # rescue_clause
# else
# else_body
# end
class Rescue < Base
include ExceptionHandler
define_predicate :main_body?, child_index: 0
define_predicate :rescue_clause?, child_index: 1..-2
define_predicate :else_body?, child_index: -1
def always_run?
false
end
end
# begin
# main_body
# ensure
# ensure_body
# end
class Ensure < Base
include ExceptionHandler
define_predicate :main_body?, child_index: 0
define_predicate :ensure_body?, child_index: -1
def always_run?
ensure_body?
end
end
CLASSES_BY_TYPE = Base.classes.each_with_object({}) do |klass, classes|
classes[klass.type] = klass
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/core.rb | lib/rubocop/server/core.rb | # frozen_string_literal: true
require 'securerandom'
require 'socket'
require 'stringio'
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
# The core of server process. It starts TCP server and perform socket communication.
# @api private
class Core
JSON_FORMATS = %w[json j].freeze
def self.token
@token ||= SecureRandom.hex(4)
end
def token
self.class.token
end
def start(host, port, detach: true)
$PROGRAM_NAME = "rubocop --server #{Cache.project_dir}"
require_relative '../../rubocop'
start_server(host, port)
return unless server_mode?
detach ? detach_server : run_server
end
private
def detach_server
write_port_and_token_files
pid = fork do
if defined?(RubyVM::YJIT.enable)
RubyVM::YJIT.enable
end
Process.daemon(true)
$stderr.reopen(Cache.stderr_path, 'w')
process_input
end
Process.waitpid(pid)
end
def write_port_and_token_files
Cache.write_port_and_token_files(port: @server.addr[1], token: token)
end
def process_input
Cache.write_pid_file do
read_socket(@server.accept) until @server.closed?
end
end
def run_server
write_port_and_token_files
process_input
end
def server_mode?
true
end
def start_server(host, port)
@server = TCPServer.open(host, port)
# JSON format does not expected output message when IDE integration with server mode.
# See: https://github.com/rubocop/rubocop/issues/11164
return if use_json_format?
output_stream = ARGV.include?('--stderr') ? $stderr : $stdout
output_stream.puts "RuboCop server starting on #{@server.addr[3]}:#{@server.addr[1]}."
end
def read_socket(socket)
SocketReader.new(socket).read!
rescue InvalidTokenError
socket.puts 'token is not valid.'
rescue ServerStopRequest
@server.close
rescue UnknownServerCommandError => e
socket.puts e.message
rescue Errno::EPIPE => e
warn e.inspect
rescue StandardError => e
socket.puts e.full_message
ensure
socket.close
end
def use_json_format?
return true if ARGV.include?('--format=json') || ARGV.include?('--format=j')
return false unless (index = ARGV.index('--format') || ARGV.index('-f'))
format = ARGV[index + 1]
JSON_FORMATS.include?(format)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/errors.rb | lib/rubocop/server/errors.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
# @api private
class InvalidTokenError < StandardError; end
# @api private
class ServerStopRequest < StandardError; end
# @api private
class UnknownServerCommandError < StandardError; end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/client_command.rb | lib/rubocop/server/client_command.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
autoload :Version, 'rubocop/version'
module Server
# @api private
module ClientCommand
autoload :Base, 'rubocop/server/client_command/base'
autoload :Exec, 'rubocop/server/client_command/exec'
autoload :Restart, 'rubocop/server/client_command/restart'
autoload :Start, 'rubocop/server/client_command/start'
autoload :Status, 'rubocop/server/client_command/status'
autoload :Stop, 'rubocop/server/client_command/stop'
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/socket_reader.rb | lib/rubocop/server/socket_reader.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
# This class sends the request read from the socket to server.
# @api private
class SocketReader
Request = Struct.new(:header, :body)
Header = Struct.new(:token, :cwd, :command, :args)
def initialize(socket)
@socket = socket
end
def read!
request = parse_request(@socket.read)
stderr = StringIO.new
Helper.redirect(
stdin: StringIO.new(request.body),
stdout: @socket,
stderr: stderr
) do
create_command_instance(request).run
end
ensure
Cache.stderr_path.write(stderr.string)
@socket.close
end
private
def parse_request(content)
raw_header, *body = content.lines
Request.new(parse_header(raw_header), body.join)
end
def parse_header(header)
token, cwd, command, *args = header.shellsplit
Header.new(token, cwd, command, args)
end
def create_command_instance(request)
klass = find_command_class(request.header.command)
klass.new(request.header.args, token: request.header.token, cwd: request.header.cwd)
end
def find_command_class(command)
case command
when 'stop' then ServerCommand::Stop
when 'exec' then ServerCommand::Exec
else
raise UnknownServerCommandError, "#{command.inspect} is not a valid command"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/cli.rb | lib/rubocop/server/cli.rb | # frozen_string_literal: true
require_relative '../arguments_env'
require_relative '../arguments_file'
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
# The CLI is a class responsible of handling server command line interface logic.
# @api private
class CLI
# Same exit status value as `RuboCop::CLI`.
STATUS_SUCCESS = 0
STATUS_ERROR = 2
SERVER_OPTIONS = %w[
--server
--no-server
--server-status
--restart-server
--start-server
--stop-server
--no-detach
].freeze
EXCLUSIVE_OPTIONS = (SERVER_OPTIONS - %w[--server --no-server]).freeze
NO_DETACH_OPTIONS = %w[--server --start-server --restart-server].freeze
def initialize
@exit = false
end
def run(argv = ARGV)
unless Server.support_server?
return error('RuboCop server is not supported by this Ruby.') if use_server_option?(argv)
return STATUS_SUCCESS
end
Cache.cache_root_path = fetch_cache_root_path_from(argv)
process_arguments(argv)
end
def exit?
@exit
end
private
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
def process_arguments(argv)
server_arguments = delete_server_argument_from(argv)
detach = !server_arguments.delete('--no-detach')
if server_arguments.size >= 2
return error("#{server_arguments.join(', ')} cannot be specified together.")
end
server_command = server_arguments.first
unless detach || NO_DETACH_OPTIONS.include?(server_command)
return error("#{server_command} cannot be combined with --no-detach.")
end
if EXCLUSIVE_OPTIONS.include?(server_command) && argv.count > allowed_option_count
return error("#{server_command} cannot be combined with #{argv[0]}.")
end
if server_command.nil?
server_command = ArgumentsEnv.read_as_arguments.delete('--server') ||
ArgumentsFile.read_as_arguments.delete('--server')
end
run_command(server_command, detach: detach)
STATUS_SUCCESS
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength
def run_command(server_command, detach:)
case server_command
when '--server'
Server::ClientCommand::Start.new(detach: detach).run unless Server.running?
when '--no-server'
Server::ClientCommand::Stop.new.run if Server.running?
when '--restart-server'
@exit = true
Server::ClientCommand::Restart.new.run
when '--start-server'
@exit = true
Server::ClientCommand::Start.new(detach: detach).run
when '--stop-server'
@exit = true
Server::ClientCommand::Stop.new.run
when '--server-status'
@exit = true
Server::ClientCommand::Status.new.run
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/MethodLength
def fetch_cache_root_path_from(arguments)
cache_root = arguments.detect { |argument| argument.start_with?('--cache-root') }
return unless cache_root
if cache_root.start_with?('--cache-root=')
cache_root.split('=')[1]
else
arguments[arguments.index(cache_root) + 1]
end
end
def delete_server_argument_from(all_arguments)
SERVER_OPTIONS.each_with_object([]) do |server_option, server_arguments|
server_arguments << all_arguments.delete(server_option)
end.compact
end
def use_server_option?(argv)
(argv & SERVER_OPTIONS).any?
end
def allowed_option_count
Cache.cache_root_path ? 2 : 1
end
def error(message)
require 'rainbow'
@exit = true
warn Rainbow(message).red
STATUS_ERROR
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/server_command.rb | lib/rubocop/server/server_command.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
# @api private
module ServerCommand
autoload :Base, 'rubocop/server/server_command/base'
autoload :Exec, 'rubocop/server/server_command/exec'
autoload :Stop, 'rubocop/server/server_command/stop'
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/helper.rb | lib/rubocop/server/helper.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
# This module has a helper method for `RuboCop::Server::SocketReader`.
# @api private
module Helper
def self.redirect(stdin: $stdin, stdout: $stdout, stderr: $stderr, &_block)
old_stdin = $stdin.dup
old_stdout = $stdout.dup
old_stderr = $stderr.dup
$stdin = stdin
$stdout = stdout
$stderr = stderr
yield
ensure
$stdin = old_stdin
$stdout = old_stdout
$stderr = old_stderr
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/cache.rb | lib/rubocop/server/cache.rb | # frozen_string_literal: true
require 'digest'
require 'pathname'
require 'yaml'
require_relative '../cache_config'
require_relative '../config_finder'
require_relative '../path_util'
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
# Caches the states of server process.
# @api private
class Cache
GEMFILE_NAMES = %w[Gemfile gems.rb].freeze
LOCKFILE_NAMES = %w[Gemfile.lock gems.locked].freeze
class << self
attr_accessor :cache_root_path
# Searches for Gemfile or gems.rb in the current dir or any parent dirs
def project_dir
current_dir = Dir.pwd
while current_dir != '/'
return current_dir if GEMFILE_NAMES.any? do |gemfile|
File.exist?(File.join(current_dir, gemfile))
end
current_dir = File.expand_path('..', current_dir)
end
# If we can't find a Gemfile, just use the current directory
Dir.pwd
end
def project_dir_cache_key
@project_dir_cache_key ||= project_dir[1..].tr('/', '+')
end
# rubocop:disable Metrics/AbcSize
def restart_key(args_config_file_path: nil)
lockfile_path = LOCKFILE_NAMES.map do |lockfile_name|
Pathname(project_dir).join(lockfile_name)
end.find(&:exist?)
version_data = lockfile_path&.read || RuboCop::Version::STRING
config_data = Pathname(
args_config_file_path || ConfigFinder.find_config_path(Dir.pwd)
).read
yaml = load_erb_templated_yaml(config_data)
inherit_from_data = inherit_from_data(yaml)
require_data = require_data(yaml)
Digest::SHA1.hexdigest(version_data + config_data + inherit_from_data + require_data)
end
# rubocop:enable Metrics/AbcSize
def dir
Pathname.new(File.join(cache_path, project_dir_cache_key)).tap do |d|
d.mkpath unless d.exist?
end
end
def cache_path
cache_root_dir = if cache_root_path
File.join(cache_root_path, 'rubocop_cache')
else
cache_root_dir_from_config
end
File.expand_path(File.join(cache_root_dir, 'server'))
end
def cache_root_dir_from_config
CacheConfig.root_dir do
# `RuboCop::ConfigStore` has heavy dependencies, this is a lightweight implementation
# so that only the necessary `CacheRootDirectory` can be obtained.
config_path = ConfigFinder.find_config_path(Dir.pwd)
file_contents = File.read(config_path)
# Returns early if `CacheRootDirectory` is not used before requiring `erb` or `yaml`.
next unless file_contents.include?('CacheRootDirectory')
config_yaml = load_erb_templated_yaml(file_contents)
# For compatibility with Ruby 3.0 or lower.
if Gem::Version.new(Psych::VERSION) < Gem::Version.new('4.0.0')
config_yaml == false ? nil : config_yaml
end
config_yaml&.dig('AllCops', 'CacheRootDirectory')
end
end
def port_path
dir.join('port')
end
def token_path
dir.join('token')
end
def pid_path
dir.join('pid')
end
def lock_path
dir.join('lock')
end
def status_path
dir.join('status')
end
def version_path
dir.join('version')
end
def stderr_path
dir.join('stderr')
end
def pid_running?
Process.kill(0, pid_path.read.to_i) == 1
rescue Errno::ESRCH, Errno::ENOENT, Errno::EACCES, Errno::EROFS, Errno::ENAMETOOLONG
false
end
def acquire_lock
lock_file = File.open(lock_path, File::CREAT)
# flock returns 0 if successful, and false if not.
flock_result = lock_file.flock(File::LOCK_EX | File::LOCK_NB)
yield flock_result != false
ensure
lock_file.flock(File::LOCK_UN)
lock_file.close
end
def write_port_and_token_files(port:, token:)
port_path.write(port)
token_path.write(token)
end
def write_pid_file
pid_path.write(Process.pid)
yield
ensure
dir.rmtree
end
def write_status_file(status)
status_path.write(status)
end
def write_version_file(version)
version_path.write(version)
end
def inherit_from_data(yaml)
return '' unless (inherit_from_paths = yaml['inherit_from'])
Array(inherit_from_paths).map do |path|
next if PathUtil.remote_file?(path)
path = Pathname(path)
path.exist? ? path.read : ''
end.join
end
def require_data(yaml)
return '' unless (require_paths = yaml['require'])
Array(require_paths).map do |path|
# NOTE: This targets only relative or absolute path specifications.
# For example, specifications like `require: rubocop-performance`,
# which can be loaded from `$LOAD_PATH`, are ignored.
next unless path.start_with?('.', '/')
# NOTE: `.so` files are not typically specified, so only `.rb` files are targeted.
path = "#{path}.rb" unless path.end_with?('.rb')
path = Pathname(path)
path.exist? ? path.read : ''
end.join
end
private
def load_erb_templated_yaml(content)
require 'erb'
yaml_code = ERB.new(content).result
require 'yaml'
YAML.safe_load(yaml_code, permitted_classes: [Regexp, Symbol], aliases: true)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/server_command/exec.rb | lib/rubocop/server/server_command/exec.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ServerCommand
# This class is a server command to execute `rubocop` command using `RuboCop::CLI.new#run`.
# @api private
class Exec < Base
def run
# RuboCop output is colorized by default where there is a TTY.
# We must pass the --color option to preserve this behavior.
@args.unshift('--color') unless %w[--color --no-color].any? { |f| @args.include?(f) }
status = RuboCop::CLI.new.run(@args)
# This status file is read by `rubocop --server` (`RuboCop::Server::ClientCommand::Exec`).
# so that they use the correct exit code.
# Status is 1 when there are any issues, and 0 otherwise.
Cache.write_status_file(status)
rescue SystemExit
Cache.write_status_file(1)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/server_command/base.rb | lib/rubocop/server/server_command/base.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ServerCommand
# Abstract base class for server command.
# @api private
class Base
# Common functionality for working with subclasses of this class.
# @api private
module Runner
def run
validate_token!
Dir.chdir(@cwd) do
super
end
end
end
def self.inherited(child)
super
child.prepend Runner
end
def initialize(args, token: '', cwd: Dir.pwd)
@args = args
@token = token
@cwd = cwd
end
def run; end
private
def validate_token!
raise InvalidTokenError unless Cache.token_path.read == @token
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/server_command/stop.rb | lib/rubocop/server/server_command/stop.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ServerCommand
# This class is a server command to stop server process.
# @api private
class Stop < Base
def run
raise ServerStopRequest
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/client_command/start.rb | lib/rubocop/server/client_command/start.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ClientCommand
# This class is a client command to start server process.
# @api private
class Start < Base
def initialize(detach: true)
@detach = detach
super()
end
def run
if Server.running?
warn "RuboCop server (#{Cache.pid_path.read}) is already running."
return
end
Cache.acquire_lock do |locked|
unless locked
# Another process is already starting server,
# so wait for it to be ready.
Server.wait_for_running_status!(true)
exit 0
end
write_version_file
host = ENV.fetch('RUBOCOP_SERVER_HOST', '127.0.0.1')
port = ENV.fetch('RUBOCOP_SERVER_PORT', 0)
Server::Core.new.start(host, port, detach: @detach)
end
end
private
def write_version_file
Cache.write_version_file(
Cache.restart_key(
args_config_file_path: self.class.args_config_file_path
)
)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/client_command/exec.rb | lib/rubocop/server/client_command/exec.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ClientCommand
# This class is a client command to execute server process.
# @api private
class Exec < Base
def run
ensure_server!
read_stdin = ARGV.include?('-s') || ARGV.include?('--stdin')
send_request(
command: 'exec',
args: ARGV.dup,
body: read_stdin ? $stdin.read : ''
)
warn stderr unless stderr.empty?
status
end
private
def ensure_server!
if incompatible_version?
warn 'RuboCop version incompatibility found, RuboCop server restarting...'
ClientCommand::Stop.new.run
elsif check_running_server
return
end
ClientCommand::Start.new.run
end
def incompatible_version?
Cache.version_path.read !=
Cache.restart_key(args_config_file_path: self.class.args_config_file_path)
end
def stderr
Cache.stderr_path.read
end
def status
unless Cache.status_path.file?
raise "RuboCop server: Could not find status file at: #{Cache.status_path}"
end
status = Cache.status_path.read
raise "RuboCop server: '#{status}' is not a valid status!" unless /\A\d+\z/.match?(status)
status.to_i
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/client_command/base.rb | lib/rubocop/server/client_command/base.rb | # frozen_string_literal: true
require 'shellwords'
require 'socket'
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ClientCommand
# Abstract base class for server client command.
# @api private
class Base
def run
raise NotImplementedError
end
private
def send_request(command:, args: [], body: '')
TCPSocket.open('127.0.0.1', Cache.port_path.read) do |socket|
socket.puts [Cache.token_path.read, Dir.pwd, command, *args].shelljoin
socket.write body
socket.close_write
$stdout.write socket.readpartial(4096) until socket.eof?
end
end
def check_running_server
Server.running?.tap do |running|
warn 'RuboCop server is not running.' unless running
end
end
class << self
def args_config_file_path
first_args_config_key_index = ARGV.index { |value| ['-c', '--config'].include?(value) }
return if first_args_config_key_index.nil?
ARGV[first_args_config_key_index + 1]
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/client_command/stop.rb | lib/rubocop/server/client_command/stop.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ClientCommand
# This class is a client command to stop server process.
# @api private
class Stop < Base
def run
return unless check_running_server
pid = fork do
send_request(command: 'stop')
Server.wait_for_running_status!(false)
end
Process.waitpid(pid)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/client_command/status.rb | lib/rubocop/server/client_command/status.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ClientCommand
# This class is a client command to show server process status.
# @api private
class Status < Base
def run
if Server.running?
puts "RuboCop server (#{Cache.pid_path.read}) is running."
else
puts 'RuboCop server is not running.'
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server/client_command/restart.rb | lib/rubocop/server/client_command/restart.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
module Server
module ClientCommand
# This class is a client command to restart server process.
# @api private
class Restart < Base
def run
ClientCommand::Stop.new.run
ClientCommand::Start.new.run
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command.rb | lib/rubocop/cli/command.rb | # frozen_string_literal: true
module RuboCop
class CLI
# Home of subcommands in the CLI.
# @api private
module Command
class << self
# Find the command with a given name and run it in an environment.
def run(env, name)
class_for(name).new(env).run
end
private
def class_for(name)
Base.by_command_name(name)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/environment.rb | lib/rubocop/cli/environment.rb | # frozen_string_literal: true
module RuboCop
class CLI
# Execution environment for a CLI command.
# @api private
class Environment
attr_reader :options, :config_store, :paths
def initialize(options, config_store, paths)
@options = options
@config_store = config_store
@paths = paths
end
# Run a command in this environment.
def run(name)
Command.run(self, name)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/version.rb | lib/rubocop/cli/command/version.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# Display version.
# @api private
class Version < Base
self.command_name = :version
def run
puts RuboCop::Version::STRING if @options[:version]
puts RuboCop::Version.verbose(env: env) if @options[:verbose_version]
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/show_docs_url.rb | lib/rubocop/cli/command/show_docs_url.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# Prints out url to documentation of provided cops
# or documentation base url by default.
# @api private
class ShowDocsUrl < Base
self.command_name = :show_docs_url
def initialize(env)
super
@config = @config_store.for(Dir.pwd)
end
def run
print_documentation_url
end
private
def print_documentation_url
puts Cop::Documentation.default_base_url if cops_array.empty?
cops_array.each do |cop_name|
cop = registry_hash[cop_name]
next if cop.empty?
url = Cop::Documentation.url_for(cop.first, @config)
puts url if url
end
puts
end
def cops_array
@cops_array ||= @options[:show_docs_url]
end
def registry_hash
@registry_hash ||= Cop::Registry.global.to_h
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/lsp.rb | lib/rubocop/cli/command/lsp.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# Start Language Server Protocol of RuboCop.
# @api private
class LSP < Base
self.command_name = :lsp
def run
# Load on demand, `languge-server-protocol` is heavy to require.
require_relative '../../lsp/server'
RuboCop::LSP::Server.new(@config_store).start
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/execute_runner.rb | lib/rubocop/cli/command/execute_runner.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# Run all the selected cops and report the result.
# @api private
class ExecuteRunner < Base
include Formatter::TextUtil
# Combination of short and long formatter names.
INTEGRATION_FORMATTERS = %w[h html j json ju junit].freeze
self.command_name = :execute_runner
def run
execute_runner(@paths)
end
private
def execute_runner(paths)
runner = Runner.new(@options, @config_store)
all_pass_or_excluded = with_redirect do
all_passed = runner.run(paths)
display_summary(runner)
all_passed || @options[:auto_gen_config]
end
maybe_print_corrected_source
if runner.aborting?
STATUS_INTERRUPTED
elsif all_pass_or_excluded && runner.errors.empty?
STATUS_SUCCESS
else
STATUS_OFFENSES
end
end
def with_redirect
if @options[:stderr]
orig_stdout = $stdout
begin
$stdout = $stderr
yield
ensure
$stdout = orig_stdout
end
else
yield
end
end
def display_summary(runner)
display_warning_summary(runner.warnings)
display_error_summary(runner.errors)
end
def display_warning_summary(warnings)
return if warnings.empty?
warn Rainbow("\n#{pluralize(warnings.size, 'warning')}:").yellow
warnings.each { |warning| warn warning }
end
def display_error_summary(errors)
return if errors.empty?
warn Rainbow("\n#{pluralize(errors.size, 'error')} occurred:").red
errors.each { |error| warn Rainbow(error).red }
warn Rainbow(<<~WARNING.strip).yellow
Errors are usually caused by RuboCop bugs.
Please, update to the latest RuboCop version if not already in use, and report a bug if the issue still occurs on this version.
#{bug_tracker_uri}
Mention the following information in the issue report:
#{RuboCop::Version.verbose}
WARNING
end
def bug_tracker_uri
return unless Gem.loaded_specs.key?('rubocop')
"#{Gem.loaded_specs['rubocop'].metadata['bug_tracker_uri']}\n"
end
def maybe_print_corrected_source
# Integration tools (like RubyMine) expect to have only the JSON result
# when specifying JSON format. Similar HTML and JUnit are targeted as well.
# See: https://github.com/rubocop/rubocop/issues/8673
return if INTEGRATION_FORMATTERS.include?(@options[:format])
return unless @options[:stdin] && @options[:autocorrect]
(@options[:stderr] ? $stderr : $stdout).puts '=' * 20
print @options[:stdin]
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/auto_generate_config.rb | lib/rubocop/cli/command/auto_generate_config.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# Generate a configuration file acting as a TODO list.
# @api private
class AutoGenerateConfig < Base
self.command_name = :auto_gen_config
AUTO_GENERATED_FILE = '.rubocop_todo.yml'
YAML_OPTIONAL_DOC_START = /\A---(\s+#|\s*\z)/.freeze
PLACEHOLDER = '###rubocop:inherit_here'
PHASE_1 = 'Phase 1 of 2: run Layout/LineLength cop'
PHASE_2 = 'Phase 2 of 2: run all cops'
PHASE_1_OVERRIDDEN = '(skipped because the default Layout/LineLength:Max is overridden)'
PHASE_1_DISABLED = '(skipped because Layout/LineLength is disabled)'
PHASE_1_SKIPPED_ONLY_COPS =
'(skipped because a list of cops is passed to the `--only` flag)'
PHASE_1_SKIPPED_ONLY_EXCLUDE =
'(skipped because only excludes will be generated due to `--auto-gen-only-exclude` flag)'
def run
add_formatter
reset_config_and_auto_gen_file
line_length_contents = maybe_run_line_length_cop
run_all_cops(line_length_contents)
end
private
def maybe_run_line_length_cop
if only_exclude?
skip_line_length_cop(PHASE_1_SKIPPED_ONLY_EXCLUDE)
elsif !line_length_enabled?(@config_store.for_pwd)
skip_line_length_cop(PHASE_1_DISABLED)
elsif !same_max_line_length?(@config_store.for_pwd, ConfigLoader.default_configuration)
skip_line_length_cop(PHASE_1_OVERRIDDEN)
elsif options_has_only_flag?
skip_line_length_cop(PHASE_1_SKIPPED_ONLY_COPS)
else
run_line_length_cop
end
end
def skip_line_length_cop(reason)
puts Rainbow("#{PHASE_1} #{reason}").yellow
''
end
def line_length_enabled?(config)
line_length_cop(config)['Enabled']
end
def same_max_line_length?(config1, config2)
max_line_length(config1) == max_line_length(config2)
end
def max_line_length(config)
line_length_cop(config)['Max']
end
def line_length_cop(config)
config.for_cop('Layout/LineLength')
end
def options_has_only_flag?
@options[:only]
end
def only_exclude?
@options[:auto_gen_only_exclude]
end
# Do an initial run with only Layout/LineLength so that cops that
# depend on Layout/LineLength:Max get the correct value for that
# parameter.
def run_line_length_cop
puts Rainbow(PHASE_1).yellow
@options[:only] = ['Layout/LineLength']
execute_runner
@options.delete(:only)
@config_store = ConfigStore.new
@config_store.apply_options!(@options)
# Save the todo configuration of the LineLength cop.
File.read(AUTO_GENERATED_FILE).lines.drop_while { |line| line.start_with?('#') }.join
end
def run_all_cops(line_length_contents)
puts Rainbow(PHASE_2).yellow
result = execute_runner
# This run was made with the current maximum length allowed, so append
# the saved setting for LineLength.
File.open(AUTO_GENERATED_FILE, 'a') { |f| f.write(line_length_contents) }
result
end
def reset_config_and_auto_gen_file
@config_store = ConfigStore.new
@config_store.apply_options!(@options)
File.open(AUTO_GENERATED_FILE, 'w') {} # create or truncate if exists
add_inheritance_from_auto_generated_file(@options[:config])
end
def add_formatter
@options[:formatters] << [Formatter::DisabledConfigFormatter, AUTO_GENERATED_FILE]
end
def execute_runner
Environment.new(@options, @config_store, @paths).run(:execute_runner)
end
def add_inheritance_from_auto_generated_file(config_file)
file_string = " #{relative_path_to_todo_from_options_config}"
config_file ||= ConfigFinder::DOTFILE
if File.exist?(config_file)
files = Array(ConfigLoader.load_yaml_configuration(config_file)['inherit_from'])
return if files.include?(relative_path_to_todo_from_options_config)
files.unshift(relative_path_to_todo_from_options_config)
file_string = "\n - #{files.join("\n - ")}" if files.size > 1
rubocop_yml_contents = existing_configuration(config_file)
end
write_config_file(config_file, file_string, rubocop_yml_contents)
puts "Added inheritance from `#{relative_path_to_todo_from_options_config}` " \
"in `#{ConfigFinder::DOTFILE}`."
end
def existing_configuration(config_file)
File.read(config_file, encoding: Encoding::UTF_8)
.sub(/^inherit_from: *[^\n]+/, PLACEHOLDER)
.sub(/^inherit_from: *(\n *- *[^\n]+)+/, PLACEHOLDER)
end
def write_config_file(file_name, file_string, rubocop_yml_contents)
lines = /\S/.match?(rubocop_yml_contents) ? rubocop_yml_contents.split("\n", -1) : []
unless rubocop_yml_contents&.include?(PLACEHOLDER)
doc_start_index = lines.index { |line| YAML_OPTIONAL_DOC_START.match?(line) } || -1
lines.insert(doc_start_index + 1, PLACEHOLDER)
end
File.write(file_name, lines.join("\n")
.sub(/#{PLACEHOLDER}\n*/o, "inherit_from:#{file_string}\n\n")
.sub(/\n\n+\Z/, "\n"))
end
def relative_path_to_todo_from_options_config
return AUTO_GENERATED_FILE unless @options[:config]
base = Pathname.new(Dir.pwd)
config_dir = Pathname.new(@options[:config]).realpath.dirname
# Don't have the path start with `/`
return AUTO_GENERATED_FILE if config_dir == base
"#{base.relative_path_from(config_dir)}/#{AUTO_GENERATED_FILE}"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/base.rb | lib/rubocop/cli/command/base.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# A subcommand in the CLI.
# @api private
class Base
attr_reader :env
@subclasses = []
class << self
attr_accessor :command_name
def inherited(subclass)
super
@subclasses << subclass
end
def by_command_name(name)
@subclasses.detect { |s| s.command_name == name }
end
end
def initialize(env)
@env = env
@options = env.options
@config_store = env.config_store
@paths = env.paths
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/show_cops.rb | lib/rubocop/cli/command/show_cops.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# Shows the given cops, or all cops by default, and their configurations
# for the current directory.
# @api private
class ShowCops < Base
self.command_name = :show_cops
ExactMatcher = Struct.new(:pattern) do
def match?(name)
name == pattern
end
end
WildcardMatcher = Struct.new(:pattern) do
def match?(name)
File.fnmatch(pattern, name, File::FNM_PATHNAME)
end
end
def initialize(env)
super
# Load the configs so the require()s are done for custom cops
@config = @config_store.for(Dir.pwd)
@cop_matchers = @options[:show_cops].map do |pattern|
if pattern.include?('*')
WildcardMatcher.new(pattern)
else
ExactMatcher.new(pattern)
end
end
end
def run
print_available_cops
end
private
def print_available_cops
registry = Cop::Registry.global
show_all = @cop_matchers.empty?
puts "# Available cops (#{registry.length}) + config for #{Dir.pwd}: " if show_all
registry.departments.sort!.each do |department|
print_cops_of_department(registry, department, show_all)
end
end
def print_cops_of_department(registry, department, show_all)
selected_cops = if show_all
cops_of_department(registry, department)
else
selected_cops_of_department(registry, department)
end
puts "# Department '#{department}' (#{selected_cops.length}):" if show_all
print_cop_details(selected_cops)
end
def print_cop_details(cops)
cops.each do |cop|
puts '# Supports --autocorrect' if cop.support_autocorrect?
puts "#{cop.cop_name}:"
puts config_lines(cop)
puts
end
end
def selected_cops_of_department(cops, department)
cops_of_department(cops, department).select do |cop|
@cop_matchers.any? do |matcher|
matcher.match?(cop.cop_name)
end
end
end
def cops_of_department(cops, department)
cops.with_department(department).sort!
end
def config_lines(cop)
cnf = @config.for_cop(cop)
cnf.to_yaml.lines.to_a.drop(1).map { |line| " #{line}" }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/suggest_extensions.rb | lib/rubocop/cli/command/suggest_extensions.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# Suggest RuboCop extensions to install based on Gemfile dependencies.
# Only primary dependencies are evaluated, so if a dependency depends on a
# gem with an extension, it is not suggested. However, if an extension is
# a transitive dependency, it will not be suggested.
# @api private
class SuggestExtensions < Base
# Combination of short and long formatter names.
INCLUDED_FORMATTERS = %w[p progress fu fuubar pa pacman].freeze
self.command_name = :suggest_extensions
def run
return if skip? || extensions.none?
print_install_suggestions if not_installed_extensions.any?
print_load_suggestions if installed_and_not_loaded_extensions.any?
print_opt_out_instruction
puts if @options[:display_time]
end
private
def skip?
# Disable outputting the notification:
# 1. On CI
# 2. When given RuboCop options that it doesn't make sense for
# 3. For all formatters except specified in `INCLUDED_FORMATTERS'`
ENV.fetch('CI', nil) ||
@options[:only] || @options[:debug] || @options[:list_target_files] ||
@options[:out] || @options[:stdin] ||
!INCLUDED_FORMATTERS.include?(current_formatter)
end
def print_install_suggestions
puts
puts 'Tip: Based on detected gems, the following ' \
'RuboCop extension libraries might be helpful:'
not_installed_extensions.sort.each do |extension|
puts " * #{extension} (https://rubygems.org/gems/#{extension})"
end
end
def print_load_suggestions
puts
puts 'The following RuboCop extension libraries are installed but not loaded in config:'
installed_and_not_loaded_extensions.sort.each do |extension|
puts " * #{extension}"
end
end
def print_opt_out_instruction
puts
puts 'You can opt out of this message by adding the following to your config ' \
'(see https://docs.rubocop.org/rubocop/extensions.html#extension-suggestions ' \
'for more options):'
puts ' AllCops:'
puts ' SuggestExtensions: false'
end
def current_formatter
@options[:format] || @config_store.for_pwd.for_all_cops['DefaultFormatter'] || 'p'
end
def all_extensions
return [] unless lockfile.dependencies.any?
extensions = @config_store.for_pwd.for_all_cops['SuggestExtensions']
case extensions
when true
extensions = ConfigLoader.default_configuration.for_all_cops['SuggestExtensions']
when false, nil
extensions = {}
end
extensions.select { |_, v| (Array(v) & dependent_gems).any? }.keys
end
def extensions
not_installed_extensions + installed_and_not_loaded_extensions
end
def installed_extensions
all_extensions & installed_gems
end
def not_installed_extensions
all_extensions - installed_gems
end
def loaded_extensions
rubocop_config = @config_store.for_pwd
plugin_names = rubocop_config.loaded_plugins.map do |plugin|
plugin.about.name
end
plugin_names + rubocop_config.loaded_features.to_a
end
def installed_and_not_loaded_extensions
installed_extensions - loaded_extensions
end
def lockfile
@lockfile ||= Lockfile.new
end
def dependent_gems
lockfile.dependencies.map(&:name)
end
def installed_gems
lockfile.gems.map(&:name)
end
def puts(*args)
output = (@options[:stderr] ? $stderr : $stdout)
output.puts(*args)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli/command/init_dotfile.rb | lib/rubocop/cli/command/init_dotfile.rb | # frozen_string_literal: true
module RuboCop
class CLI
module Command
# Generate a .rubocop.yml file in the current directory.
# @api private
class InitDotfile < Base
DOTFILE = ConfigFinder::DOTFILE
self.command_name = :init
def run
path = File.expand_path(DOTFILE)
if File.exist?(DOTFILE)
warn Rainbow("#{DOTFILE} already exists at #{path}").red
STATUS_ERROR
else
description = <<~DESC
# The behavior of RuboCop can be controlled via the .rubocop.yml
# configuration file. It makes it possible to enable/disable
# certain cops (checks) and to alter their behavior if they accept
# any parameters. The file can be placed either in your home
# directory or in some project directory.
#
# RuboCop will start looking for the configuration file in the directory
# where the inspected file is and continue its way up to the root directory.
#
# See https://docs.rubocop.org/rubocop/configuration
DESC
File.write(DOTFILE, description)
puts "Writing new #{DOTFILE} to #{path}"
STATUS_SUCCESS
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/ruby_lsp/rubocop/addon.rb | lib/ruby_lsp/rubocop/addon.rb | # frozen_string_literal: true
require_relative '../../rubocop'
require_relative '../../rubocop/lsp/logger'
require_relative 'runtime_adapter'
module RubyLsp
module RuboCop
# A Ruby LSP add-on for RuboCop.
class Addon < RubyLsp::Addon
RESTART_WATCHERS = %w[.rubocop.yml .rubocop_todo.yml .rubocop].freeze
def initialize
super
@runtime_adapter = nil
end
def name
'RuboCop'
end
def version
::RuboCop::Version::STRING
end
def activate(global_state, message_queue)
::RuboCop::LSP::Logger.log(
"Activating RuboCop LSP addon #{::RuboCop::Version::STRING}.", prefix: '[RuboCop]'
)
@runtime_adapter = RuntimeAdapter.new(message_queue)
global_state.register_formatter('rubocop', @runtime_adapter)
register_additional_file_watchers(global_state, message_queue)
::RuboCop::LSP::Logger.log(
"Initialized RuboCop LSP addon #{::RuboCop::Version::STRING}.", prefix: '[RuboCop]'
)
end
def deactivate
@runtime_adapter = nil
end
# rubocop:disable Metrics/MethodLength
def register_additional_file_watchers(global_state, message_queue)
return unless global_state.supports_watching_files
message_queue << Request.new(
id: 'rubocop-file-watcher',
method: 'client/registerCapability',
params: Interface::RegistrationParams.new(
registrations: [
Interface::Registration.new(
id: 'workspace/didChangeWatchedFilesRuboCop',
method: 'workspace/didChangeWatchedFiles',
register_options: Interface::DidChangeWatchedFilesRegistrationOptions.new(
watchers: [
Interface::FileSystemWatcher.new(
glob_pattern: "**/{#{RESTART_WATCHERS.join(',')}}",
kind: Constant::WatchKind::CREATE | Constant::WatchKind::CHANGE | Constant::WatchKind::DELETE
)
]
)
)
]
)
)
end
# rubocop:enable Metrics/MethodLength
def workspace_did_change_watched_files(changes)
if (changed_config_file = changed_config_file(changes))
@runtime_adapter.reload_config
::RuboCop::LSP::Logger.log(<<~MESSAGE, prefix: '[RuboCop]')
Re-initialized RuboCop LSP addon #{::RuboCop::Version::STRING} due to #{changed_config_file} change.
MESSAGE
end
end
private
def changed_config_file(changes)
RESTART_WATCHERS.find do |file_name|
changes.any? { |change| change[:uri].end_with?(file_name) }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/ruby_lsp/rubocop/runtime_adapter.rb | lib/ruby_lsp/rubocop/runtime_adapter.rb | # frozen_string_literal: true
require_relative '../../rubocop/lsp/runtime'
module RubyLsp
module RuboCop
# Provides an adapter to bridge RuboCop's built-in LSP runtime with Ruby LSP's add-on.
# @api private
class RuntimeAdapter
def initialize(message_queue)
@message_queue = message_queue
reload_config
end
def reload_config
@runtime = nil
options, _paths = ::RuboCop::Options.new.parse([])
config_store = ::RuboCop::ConfigStore.new
config_store.apply_options!(options)
@runtime = ::RuboCop::LSP::Runtime.new(config_store)
rescue ::RuboCop::Error => e
@message_queue << Notification.window_show_message(
"RuboCop configuration error: #{e.message}. Formatting will not be available.",
type: Constant::MessageType::ERROR
)
end
def run_diagnostic(uri, document)
with_error_handling do
@runtime.offenses(
uri_to_path(uri),
document.source,
document.encoding,
prism_result: prism_result(document)
)
end
end
def run_formatting(uri, document)
with_error_handling do
@runtime.format(
uri_to_path(uri),
document.source,
command: 'rubocop.formatAutocorrects',
prism_result: prism_result(document)
)
end
end
def run_range_formatting(_uri, _partial_source, _base_indentation)
# Not yet supported. Should return the formatted version of `partial_source` which is
# a partial selection of the entire document. For example, it should not try to add
# a frozen_string_literal magic comment and all style corrections should start from
# the `base_indentation`.
nil
end
private
def with_error_handling
return unless @runtime
yield
rescue StandardError => e
::RuboCop::LSP::Logger.log(e.full_message, prefix: '[RuboCop]')
message = if e.is_a?(::RuboCop::ErrorWithAnalyzedFileLocation)
"for the #{e.cop.name} cop"
else
"- #{e.message}"
end
raise Requests::Formatting::Error, <<~MSG
An internal error occurred #{message}.
Updating to a newer version of RuboCop may solve this.
For more details, run RuboCop on the command line.
MSG
end
# duplicated from: lib/standard/lsp/routes.rb
# modified to incorporate Ruby LSP's to_standardized_path method
def uri_to_path(uri)
if uri.respond_to?(:to_standardized_path) && (standardized_path = uri.to_standardized_path)
standardized_path
else
uri.to_s.delete_prefix('file://')
end
end
def prism_result(document)
prism_result = document.parse_result
# NOTE: `prism_result` must be `Prism::ParseLexResult` compatible object.
# This is for compatibility parsed result unsupported.
prism_result.is_a?(Prism::ParseLexResult) ? prism_result : nil
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/benchmark/large_model.rb | benchmark/large_model.rb | # frozen_string_literal: true
# gem 'grape', '=1.0.1'
require 'grape'
require 'ruby-prof'
require 'hashie'
class API < Grape::API
# include Grape::Extensions::Hash::ParamBuilder
# include Grape::Extensions::Hashie::Mash::ParamBuilder
rescue_from do |e|
warn "\n\n#{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}\n\n"
end
prefix :api
version 'v1', using: :path
content_type :json, 'application/json; charset=UTF-8'
default_format :json
def self.vrp_request_timewindow(this)
this.optional(:id, types: String)
this.optional(:start, types: [String, Float, Integer])
this.optional(:end, types: [String, Float, Integer])
this.optional(:day_index, type: Integer, values: 0..6)
this.at_least_one_of :start, :end, :day_index
end
def self.vrp_request_indice_range(this)
this.optional(:start, type: Integer)
this.optional(:end, type: Integer)
end
def self.vrp_request_point(this)
this.requires(:id, type: String, allow_blank: false)
this.optional(:location, type: Hash, allow_blank: false) do
requires(:lat, type: Float, allow_blank: false)
requires(:lon, type: Float, allow_blank: false)
end
end
def self.vrp_request_unit(this)
this.requires(:id, type: String, allow_blank: false)
this.optional(:label, type: String)
this.optional(:counting, type: Boolean)
end
def self.vrp_request_activity(this)
this.optional(:duration, types: [String, Float, Integer])
this.optional(:additional_value, type: Integer)
this.optional(:setup_duration, types: [String, Float, Integer])
this.optional(:late_multiplier, type: Float)
this.optional(:timewindow_start_day_shift_number, documentation: { hidden: true }, type: Integer)
this.requires(:point_id, type: String, allow_blank: false)
this.optional(:timewindows, type: Array) do
API.vrp_request_timewindow(self)
end
end
def self.vrp_request_quantity(this)
this.optional(:id, type: String)
this.requires(:unit_id, type: String, allow_blank: false)
this.optional(:value, type: Float)
end
def self.vrp_request_capacity(this)
this.optional(:id, type: String)
this.requires(:unit_id, type: String, allow_blank: false)
this.requires(:limit, type: Float, allow_blank: false)
this.optional(:initial, type: Float)
this.optional(:overload_multiplier, type: Float)
end
def self.vrp_request_vehicle(this)
this.requires(:id, type: String, allow_blank: false)
this.optional(:cost_fixed, type: Float)
this.optional(:cost_distance_multiplier, type: Float)
this.optional(:cost_time_multiplier, type: Float)
this.optional :router_dimension, type: String, values: %w[time distance]
this.optional(:skills, type: Array[Array[String]], coerce_with: ->(val) { val.is_a?(String) ? [val.split(',').map(&:strip)] : val })
this.optional(:unavailable_work_day_indices, type: Array[Integer])
this.optional(:free_approach, type: Boolean)
this.optional(:free_return, type: Boolean)
this.optional(:start_point_id, type: String)
this.optional(:end_point_id, type: String)
this.optional(:capacities, type: Array) do
API.vrp_request_capacity(self)
end
this.optional(:sequence_timewindows, type: Array) do
API.vrp_request_timewindow(self)
end
end
def self.vrp_request_service(this)
this.requires(:id, type: String, allow_blank: false)
this.optional(:priority, type: Integer, values: 0..8)
this.optional(:exclusion_cost, type: Integer)
this.optional(:visits_number, type: Integer, coerce_with: ->(val) { val.to_i.positive? && val.to_i }, default: 1, allow_blank: false)
this.optional(:unavailable_visit_indices, type: Array[Integer])
this.optional(:unavailable_visit_day_indices, type: Array[Integer])
this.optional(:minimum_lapse, type: Float)
this.optional(:maximum_lapse, type: Float)
this.optional(:sticky_vehicle_ids, type: Array[String])
this.optional(:skills, type: Array[String])
this.optional(:type, type: Symbol)
this.optional(:activity, type: Hash) do
API.vrp_request_activity(self)
end
this.optional(:quantities, type: Array) do
API.vrp_request_quantity(self)
end
end
def self.vrp_request_configuration(this)
this.optional(:preprocessing, type: Hash) do
API.vrp_request_preprocessing(self)
end
this.optional(:resolution, type: Hash) do
API.vrp_request_resolution(self)
end
this.optional(:restitution, type: Hash) do
API.vrp_request_restitution(self)
end
this.optional(:schedule, type: Hash) do
API.vrp_request_schedule(self)
end
end
def self.vrp_request_partition(this)
this.requires(:method, type: String, values: %w[hierarchical_tree balanced_kmeans])
this.optional(:metric, type: Symbol)
this.optional(:entity, type: Symbol, values: %i[vehicle work_day], coerce_with: lambda(&:to_sym))
this.optional(:threshold, type: Integer)
end
def self.vrp_request_preprocessing(this)
this.optional(:max_split_size, type: Integer)
this.optional(:partition_method, type: String, documentation: { hidden: true })
this.optional(:partition_metric, type: Symbol, documentation: { hidden: true })
this.optional(:kmeans_centroids, type: Array[Integer])
this.optional(:cluster_threshold, type: Float)
this.optional(:force_cluster, type: Boolean)
this.optional(:prefer_short_segment, type: Boolean)
this.optional(:neighbourhood_size, type: Integer)
this.optional(:partitions, type: Array) do
API.vrp_request_partition(self)
end
this.optional(:first_solution_strategy, type: Array[String])
end
def self.vrp_request_resolution(this)
this.optional(:duration, type: Integer, allow_blank: false)
this.optional(:iterations, type: Integer, allow_blank: false)
this.optional(:iterations_without_improvment, type: Integer, allow_blank: false)
this.optional(:stable_iterations, type: Integer, allow_blank: false)
this.optional(:stable_coefficient, type: Float, allow_blank: false)
this.optional(:initial_time_out, type: Integer, allow_blank: false, documentation: { hidden: true })
this.optional(:minimum_duration, type: Integer, allow_blank: false)
this.optional(:time_out_multiplier, type: Integer)
this.optional(:vehicle_limit, type: Integer)
this.optional(:solver_parameter, type: Integer, documentation: { hidden: true })
this.optional(:solver, type: Boolean, default: true)
this.optional(:same_point_day, type: Boolean)
this.optional(:allow_partial_assignment, type: Boolean, default: true)
this.optional(:split_number, type: Integer)
this.optional(:evaluate_only, type: Boolean)
this.optional(:several_solutions, type: Integer, allow_blank: false, default: 1)
this.optional(:batch_heuristic, type: Boolean, default: false)
this.optional(:variation_ratio, type: Integer)
this.optional(:repetition, type: Integer, documentation: { hidden: true })
this.at_least_one_of :duration, :iterations, :iterations_without_improvment, :stable_iterations, :stable_coefficient, :initial_time_out, :minimum_duration
this.mutually_exclusive :initial_time_out, :minimum_duration
end
def self.vrp_request_restitution(this)
this.optional(:geometry, type: Boolean)
this.optional(:geometry_polyline, type: Boolean)
this.optional(:intermediate_solutions, type: Boolean)
this.optional(:csv, type: Boolean)
this.optional(:allow_empty_result, type: Boolean)
end
def self.vrp_request_schedule(this)
this.optional(:range_indices, type: Hash) do
API.vrp_request_indice_range(self)
end
this.optional(:unavailable_indices, type: Array[Integer])
end
params do
optional(:vrp, type: Hash, documentation: { param_type: 'body' }) do
optional(:name, type: String)
optional(:points, type: Array) do
API.vrp_request_point(self)
end
optional(:units, type: Array) do
API.vrp_request_unit(self)
end
requires(:vehicles, type: Array) do
API.vrp_request_vehicle(self)
end
optional(:services, type: Array, allow_blank: false) do
API.vrp_request_service(self)
end
optional(:configuration, type: Hash) do
API.vrp_request_configuration(self)
end
end
end
post '/' do
{
skills_v1: params[:vrp][:vehicles].first[:skills],
skills_v2: params[:vrp][:vehicles].last[:skills]
}
end
end
puts Grape::VERSION
options = {
method: Rack::POST,
params: JSON.parse(File.read('benchmark/resource/vrp_example.json'))
}
env = Rack::MockRequest.env_for('/api/v1', options)
start = Time.now
result = RubyProf.profile do
response = API.call env
puts response.last
end
puts Time.now - start
printer = RubyProf::FlatPrinter.new(result)
File.open('test_prof.out', 'w+') { |f| printer.print(f, {}) }
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/benchmark/compile_many_routes.rb | benchmark/compile_many_routes.rb | # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'grape'
require 'benchmark/ips'
class API < Grape::API
prefix :api
version 'v1', using: :path
2000.times do |index|
get "/test#{index}/" do
'hello'
end
end
end
Benchmark.ips do |ips|
ips.report('Compiling 2000 routes') do
API.compile!
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/benchmark/nested_params.rb | benchmark/nested_params.rb | # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'grape'
require 'benchmark/ips'
class API < Grape::API
prefix :api
version 'v1', using: :path
params do
requires :address, type: Hash do
requires :street, type: String
requires :postal_code, type: Integer
optional :city, type: String
end
end
post '/' do
'hello'
end
end
options = {
method: Rack::POST,
params: {
address: {
street: 'Alexis Pl.',
postal_code: '90210',
city: 'Beverly Hills'
}
}
}
env = Rack::MockRequest.env_for('/api/v1', options)
10.times do |i|
env["HTTP_HEADER#{i}"] = '123'
end
Benchmark.ips do |ips|
ips.report('POST with nested params') do
API.call env
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/benchmark/simple.rb | benchmark/simple.rb | # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'grape'
require 'benchmark/ips'
class API < Grape::API
prefix :api
version 'v1', using: :path
get '/' do
'hello'
end
end
options = {
method: Rack::GET
}
env = Rack::MockRequest.env_for('/api/v1', options)
10.times do |i|
env["HTTP_HEADER#{i}"] = '123'
end
Benchmark.ips do |ips|
ips.report('simple') do
API.call env
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/benchmark/remounting.rb | benchmark/remounting.rb | # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'grape'
require 'benchmark/memory'
class VotingApi < Grape::API
logger Logger.new($stdout)
helpers do
def logger
VotingApi.logger
end
end
namespace 'votes' do
get do
logger
end
end
end
class PostApi < Grape::API
mount VotingApi
end
class CommentAPI < Grape::API
mount VotingApi
end
env = Rack::MockRequest.env_for('/votes', method: Rack::GET)
Benchmark.memory do |api|
calls = 1000
api.report('using Array') do
VotingApi.instance_variable_set(:@setup, [])
calls.times { PostApi.call(env) }
puts " setup size: #{VotingApi.instance_variable_get(:@setup).size}"
end
api.report('using Set') do
VotingApi.instance_variable_set(:@setup, Set.new)
calls.times { PostApi.call(env) }
puts " setup size: #{VotingApi.instance_variable_get(:@setup).size}"
end
api.compare!
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/benchmark/issue_mounting.rb | benchmark/issue_mounting.rb | # frozen_string_literal: true
require 'bundler/inline'
gemfile(true) do
source 'https://rubygems.org'
gem 'grape'
gem 'rack'
gem 'minitest'
gem 'rack-test'
end
require 'minitest/autorun'
require 'rack/test'
require 'grape'
class GrapeAPIBugTest < Minitest::Test
include Rack::Test::Methods
RootAPI = Class.new(Grape::API) do
format :json
delete :test do
status 200
[]
end
end
def test_v1_users_via_api
env = Rack::MockRequest.env_for('/test', method: Rack::DELETE)
response = Rack::MockResponse[*RootAPI.call(env)]
assert_equal '[]', response.body
assert_equal 200, response.status
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'simplecov'
require 'rubygems'
require 'bundler'
Bundler.require :default, :test
Grape.deprecator.behavior = :raise
%w[config support].each do |dir|
Dir["#{File.dirname(__FILE__)}/#{dir}/**/*.rb"].each do |file|
require file
end
end
Grape.config.lint = true # lint all apis by default
Grape::Util::Registry.include(Deregister)
# The default value for this setting is true in a standard Rails app,
# so it should be set to true here as well to reflect that.
I18n.enforce_available_locales = true
RSpec.configure do |config|
config.include Rack::Test::Methods
config.include Spec::Support::Helpers
config.raise_errors_for_deprecations!
config.filter_run_when_matching :focus
config.before(:all) { Grape::Util::InheritableSetting.reset_global! }
config.before { Grape::Util::InheritableSetting.reset_global! }
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/endpoint_faker.rb | spec/support/endpoint_faker.rb | # frozen_string_literal: true
module Spec
module Support
class EndpointFaker
class FakerAPI < Grape::API
get('/')
end
def initialize(app, endpoint = FakerAPI.endpoints.first)
@app = app
@endpoint = endpoint
end
def call(env)
@endpoint.instance_exec do
@request = Grape::Request.new(env.dup)
end
@app.call(env.merge(Grape::Env::API_ENDPOINT => @endpoint))
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/cookie_jar.rb | spec/support/cookie_jar.rb | # frozen_string_literal: true
require 'uri'
module Spec
module Support
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
class CookieJar
attr_reader :attributes
def initialize(raw)
@attributes = raw.split(/;\s*/).flat_map.with_index do |attribute, i|
attribute, value = attribute.split('=', 2)
if i.zero?
[['name', attribute], ['value', unescape(value)]]
else
[[attribute.downcase, parse_value(attribute, value)]]
end
end.to_h.freeze
end
def to_h
@attributes.dup
end
def to_s
@attributes.to_s
end
private
def unescape(value)
URI.decode_www_form_component(value, Encoding::UTF_8)
end
def parse_value(attribute, value)
case attribute
when 'expires'
Time.parse(value)
when 'max-age'
value.to_i
when 'secure', 'httponly', 'partitioned'
true
else
unescape(value)
end
end
end
end
end
module Rack
class MockResponse
def cookie_jar
@cookie_jar ||= Array(headers[Rack::SET_COOKIE]).flat_map { |h| h.split("\n") }.map { |c| Spec::Support::CookieJar.new(c).to_h }
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/integer_helpers.rb | spec/support/integer_helpers.rb | # frozen_string_literal: true
module Spec
module Support
module Helpers
INTEGER_CLASS_NAME = 0.class.to_s.freeze
def integer_class_name
INTEGER_CLASS_NAME
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/chunked_response.rb | spec/support/chunked_response.rb | # frozen_string_literal: true
# this is a copy of Rack::Chunked which has been removed in rack > 3.0
class ChunkedResponse
class Body
TERM = "\r\n"
TAIL = "0#{TERM}".freeze
# Store the response body to be chunked.
def initialize(body)
@body = body
end
# For each element yielded by the response body, yield
# the element in chunked encoding.
def each(&)
term = TERM
@body.each do |chunk|
size = chunk.bytesize
next if size == 0
yield [size.to_s(16), term, chunk.b, term].join
end
yield TAIL
yield_trailers(&)
yield term
end
# Close the response body if the response body supports it.
def close
@body.close if @body.respond_to?(:close)
end
private
# Do nothing as this class does not support trailer headers.
def yield_trailers; end
end
class TrailerBody < Body
private
# Yield strings for each trailer header.
def yield_trailers
@body.trailers.each_pair do |k, v|
yield "#{k}: #{v}\r\n"
end
end
end
def initialize(app)
@app = app
end
def call(env)
status, headers, body = response = @app.call(env)
if !Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) &&
!headers[Rack::CONTENT_LENGTH] &&
!headers['Transfer-Encoding']
headers['Transfer-Encoding'] = 'chunked'
response[2] = if headers['trailer']
TrailerBody.new(body)
else
Body.new(body)
end
end
response
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/basic_auth_encode_helpers.rb | spec/support/basic_auth_encode_helpers.rb | # frozen_string_literal: true
module Spec
module Support
module Helpers
def encode_basic_auth(username, password)
"Basic #{Base64.encode64("#{username}:#{password}")}"
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/content_type_helpers.rb | spec/support/content_type_helpers.rb | # frozen_string_literal: true
module Spec
module Support
module Helpers
%w[put patch post delete].each do |method|
define_method :"#{method}_with_json" do |uri, params = {}, env = {}, &block|
params = params.to_json
env['CONTENT_TYPE'] ||= 'application/json'
__send__(method, uri, params, env, &block)
end
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/deprecated_warning_handlers.rb | spec/support/deprecated_warning_handlers.rb | # frozen_string_literal: true
Warning[:deprecated] = true
module DeprecatedWarningHandler
class DeprecationWarning < StandardError; end
DEPRECATION_REGEX = /is deprecated/
def warn(message)
return super unless message.match?(DEPRECATION_REGEX)
exception = DeprecationWarning.new(message)
exception.set_backtrace(caller)
raise exception
end
end
Warning.singleton_class.prepend(DeprecatedWarningHandler)
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/versioned_helpers.rb | spec/support/versioned_helpers.rb | # frozen_string_literal: true
# Versioning
module Spec
module Support
module Helpers
# Returns the path with options[:version] prefixed if options[:using] is :path.
# Returns normal path otherwise.
def versioned_path(options)
case options[:using]
when :path
File.join('/', options[:prefix] || '', options[:version], options[:path])
when :param, :header, :accept_version_header
File.join('/', options[:prefix] || '', options[:path])
else
raise ArgumentError.new("unknown versioning strategy: #{options[:using]}")
end
end
def versioned_headers(options)
case options[:using]
when :path, :param
{}
when :header
{
'HTTP_ACCEPT' => [
"application/vnd.#{options[:vendor]}-#{options[:version]}",
options[:format]
].compact.join('+')
}
when :accept_version_header
{
'HTTP_ACCEPT_VERSION' => options[:version].to_s
}
else
raise ArgumentError.new("unknown versioning strategy: #{options[:using]}")
end
end
def versioned_get(path, version_name, version_options)
path = versioned_path(version_options.merge(version: version_name, path: path))
headers = versioned_headers(version_options.merge(version: version_name))
params = {}
params = { version_options[:parameter] => version_name } if version_options[:using] == :param
get path, params, headers
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/file_streamer.rb | spec/support/file_streamer.rb | # frozen_string_literal: true
class FileStreamer
def initialize(file_path)
@file_path = file_path
end
def each(&blk)
File.open(@file_path, 'rb') do |file|
file.each(10, &blk)
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/support/deregister.rb | spec/support/deregister.rb | # frozen_string_literal: true
module Deregister
def deregister(key)
registry.delete(key)
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/integration/dry_validation/dry_validation_spec.rb | spec/integration/dry_validation/dry_validation_spec.rb | # frozen_string_literal: true
describe 'Dry::Schema', if: defined?(Dry::Schema) do
describe 'Grape::DSL::Validations' do
subject { app }
let(:app) do
Class.new do
extend Grape::DSL::Validations
extend Grape::DSL::Settings
end
end
describe '.contract' do
it 'saves the schema instance' do
expect(subject.contract(Dry::Schema.Params)).to be_a Grape::Validations::ContractScope
end
it 'errors without params or block' do
expect { subject.contract }.to raise_error(ArgumentError)
end
end
end
describe 'Grape::Validations::ContractScope' do
let(:validated_params) { {} }
let(:app) do
vp = validated_params
Class.new(Grape::API) do
after_validation do
vp.replace(params)
end
end
end
context 'with simple schema, pre-defined' do
let(:contract) do
Dry::Schema.Params do
required(:number).filled(:integer)
end
end
before do
app.contract(contract)
app.post('/required')
end
it 'coerces the parameter value one level deep' do
post '/required', number: '1'
expect(last_response).to be_created
expect(validated_params).to eq('number' => 1)
end
it 'shows expected validation error' do
post '/required'
expect(last_response).to be_bad_request
expect(last_response.body).to eq('number is missing')
end
end
context 'with contract class' do
let(:contract) do
Class.new(Dry::Validation::Contract) do
params do
required(:number).filled(:integer)
required(:name).filled(:string)
end
rule(:number) do
key.failure('is too high') if value > 5
end
end
end
before do
app.contract(contract)
app.post('/required')
end
it 'coerces the parameter' do
post '/required', number: '1', name: '2'
expect(last_response).to be_created
expect(validated_params).to eq('number' => 1, 'name' => '2')
end
it 'shows expected validation error' do
post '/required', number: '6'
expect(last_response).to be_bad_request
expect(last_response.body).to eq('name is missing, number is too high')
end
end
context 'with nested schema' do
before do
app.contract do
required(:home).hash do
required(:address).hash do
required(:number).filled(:integer)
end
end
required(:turns).array(:integer)
end
app.post('/required')
end
it 'keeps unknown parameters' do
post '/required', home: { address: { number: '1', street: 'Baker' } }, turns: %w[2 3]
expect(last_response).to be_created
expected = { 'home' => { 'address' => { 'number' => 1, 'street' => 'Baker' } }, 'turns' => [2, 3] }
expect(validated_params).to eq(expected)
end
it 'shows expected validation error' do
post '/required', home: { address: { something: 'else' } }
expect(last_response).to be_bad_request
expect(last_response.body).to eq('home[address][number] is missing, turns is missing')
end
end
context 'with mixed validation sources' do
before do
app.resource :foos do
route_param :foo_id, type: Integer do
contract do
required(:number).filled(:integer)
end
post('/required')
end
end
end
it 'combines the coercions' do
post '/foos/123/required', number: '1'
expect(last_response).to be_created
expected = { 'foo_id' => 123, 'number' => 1 }
expect(validated_params).to eq(expected)
end
it 'shows validation error for missing' do
post '/foos/123/required'
expect(last_response).to be_bad_request
expect(last_response.body).to eq('number is missing')
end
it 'includes keys from all sources into declared' do
declared_params = nil
app.after_validation do
declared_params = declared(params)
end
post '/foos/123/required', number: '1', string: '2'
expect(last_response).to be_created
expected = { 'foo_id' => 123, 'number' => 1 }
expect(validated_params).to eq(expected.merge('string' => '2'))
expect(declared_params).to eq(expected)
end
end
context 'with schema config validate_keys=true' do
it 'validates the whole params hash' do
app.resource :foos do
route_param :foo_id do
contract do
config.validate_keys = true
required(:number).filled(:integer)
required(:foo_id).filled(:integer)
end
post('/required')
end
end
post '/foos/123/required', number: '1'
expect(last_response).to be_created
expected = { 'foo_id' => 123, 'number' => 1 }
expect(validated_params).to eq(expected)
end
it 'fails validation for any parameters not in schema' do
app.resource :foos do
route_param :foo_id, type: Integer do
contract do
config.validate_keys = true
required(:number).filled(:integer)
end
post('/required')
end
end
post '/foos/123/required', number: '1'
expect(last_response).to be_bad_request
expect(last_response.body).to eq('foo_id is not allowed')
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/integration/rails/mounting_spec.rb | spec/integration/rails/mounting_spec.rb | # frozen_string_literal: true
describe 'Rails', if: defined?(Rails) do
context 'rails mounted' do
let(:api) do
Class.new(Grape::API) do
lint!
get('/test_grape') { 'rails mounted' }
end
end
let(:app) do
require 'rails'
require 'action_controller/railtie'
# https://github.com/rails/rails/issues/51784
# same error as described if not redefining the following
ActiveSupport::Dependencies.autoload_paths = []
ActiveSupport::Dependencies.autoload_once_paths = []
Class.new(Rails::Application) do
config.eager_load = false
config.load_defaults "#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}"
config.api_only = true
config.consider_all_requests_local = true
config.hosts << 'example.org'
routes.append do
mount GrapeApi => '/'
get 'up', to: lambda { |_env|
[200, {}, ['hello world']]
}
end
end
end
before do
stub_const('GrapeApi', api)
app.initialize!
end
it 'cascades' do
get '/test_grape'
expect(last_response).to be_successful
expect(last_response.body).to eq('rails mounted')
get '/up'
expect(last_response).to be_successful
expect(last_response.body).to eq('hello world')
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/integration/rails/railtie_spec.rb | spec/integration/rails/railtie_spec.rb | # frozen_string_literal: true
if defined?(Rails)
describe Grape::Railtie do
describe '.railtie' do
subject { test_app.deprecators[:grape] }
let(:test_app) do
# https://github.com/rails/rails/issues/51784
# same error as described if not redefining the following
ActiveSupport::Dependencies.autoload_paths = []
ActiveSupport::Dependencies.autoload_once_paths = []
Class.new(Rails::Application) do
config.eager_load = false
config.load_defaults "#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}"
end
end
before { test_app.initialize! }
it { is_expected.to be(Grape.deprecator) }
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/integration/multi_json/json_spec.rb | spec/integration/multi_json/json_spec.rb | # frozen_string_literal: true
# grape_entity depends on multi-json and it breaks the test.
describe Grape::Json, if: defined?(MultiJson) && !defined?(Grape::Entity) do
subject { described_class }
it { is_expected.to eq(MultiJson) }
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/integration/grape_entity/entity_spec.rb | spec/integration/grape_entity/entity_spec.rb | # frozen_string_literal: true
require 'rack/contrib/jsonp'
describe 'Grape::Entity', if: defined?(Grape::Entity) do
describe '#present' do
subject { Class.new(Grape::API) }
let(:app) { subject }
before do
stub_const('TestObject', Class.new)
stub_const('FakeCollection', Class.new do
def first
TestObject.new
end
end)
end
it 'sets the object as the body if no options are provided' do
inner_body = nil
subject.get '/example' do
present({ abc: 'def' })
inner_body = body
end
get '/example'
expect(inner_body).to eql(abc: 'def')
end
it 'pulls a representation from the class options if it exists' do
entity = Class.new(Grape::Entity)
allow(entity).to receive(:represent).and_return('Hiya')
subject.represent Object, with: entity
subject.get '/example' do
present Object.new
end
get '/example'
expect(last_response.body).to eq('Hiya')
end
it 'pulls a representation from the class options if the presented object is a collection of objects' do
entity = Class.new(Grape::Entity)
allow(entity).to receive(:represent).and_return('Hiya')
subject.represent TestObject, with: entity
subject.get '/example' do
present [TestObject.new]
end
subject.get '/example2' do
present FakeCollection.new
end
get '/example'
expect(last_response.body).to eq('Hiya')
get '/example2'
expect(last_response.body).to eq('Hiya')
end
it 'pulls a representation from the class ancestor if it exists' do
entity = Class.new(Grape::Entity)
allow(entity).to receive(:represent).and_return('Hiya')
subclass = Class.new(Object)
subject.represent Object, with: entity
subject.get '/example' do
present subclass.new
end
get '/example'
expect(last_response.body).to eq('Hiya')
end
it 'automatically uses Klass::Entity if that exists' do
some_model = Class.new
entity = Class.new(Grape::Entity)
allow(entity).to receive(:represent).and_return('Auto-detect!')
some_model.const_set :Entity, entity
subject.get '/example' do
present some_model.new
end
get '/example'
expect(last_response.body).to eq('Auto-detect!')
end
it 'automatically uses Klass::Entity based on the first object in the collection being presented' do
some_model = Class.new
entity = Class.new(Grape::Entity)
allow(entity).to receive(:represent).and_return('Auto-detect!')
some_model.const_set :Entity, entity
subject.get '/example' do
present [some_model.new]
end
get '/example'
expect(last_response.body).to eq('Auto-detect!')
end
it 'does not run autodetection for Entity when explicitly provided' do
entity = Class.new(Grape::Entity)
some_array = []
subject.get '/example' do
present some_array, with: entity
end
expect(some_array).not_to receive(:first)
get '/example'
end
it 'does not use #first method on ActiveRecord::Relation to prevent needless sql query' do
entity = Class.new(Grape::Entity)
some_relation = Class.new
some_model = Class.new
allow(entity).to receive(:represent).and_return('Auto-detect!')
allow(some_relation).to receive(:first)
allow(some_relation).to receive(:klass).and_return(some_model)
some_model.const_set :Entity, entity
subject.get '/example' do
present some_relation
end
expect(some_relation).not_to receive(:first)
get '/example'
expect(last_response.body).to eq('Auto-detect!')
end
it 'autodetection does not use Entity if it is not a presenter' do
some_model = Class.new
entity = Class.new
some_model.class.const_set :Entity, entity
subject.get '/example' do
present some_model
end
get '/example'
expect(entity).not_to receive(:represent)
end
it 'adds a root key to the output if one is given' do
inner_body = nil
subject.get '/example' do
present({ abc: 'def' }, root: :root)
inner_body = body
end
get '/example'
expect(inner_body).to eql(root: { abc: 'def' })
end
%i[json serializable_hash].each do |format|
it "presents with #{format}" do
entity = Class.new(Grape::Entity)
entity.root 'examples', 'example'
entity.expose :id
subject.format format
subject.get '/example' do
c = Class.new do
attr_reader :id
def initialize(id)
@id = id
end
end
present c.new(1), with: entity
end
get '/example'
expect(last_response).to be_successful
expect(last_response.body).to eq('{"example":{"id":1}}')
end
it "presents with #{format} collection" do
entity = Class.new(Grape::Entity)
entity.root 'examples', 'example'
entity.expose :id
subject.format format
subject.get '/examples' do
c = Class.new do
attr_reader :id
def initialize(id)
@id = id
end
end
examples = [c.new(1), c.new(2)]
present examples, with: entity
end
get '/examples'
expect(last_response).to be_successful
expect(last_response.body).to eq('{"examples":[{"id":1},{"id":2}]}')
end
end
it 'presents with xml' do
entity = Class.new(Grape::Entity)
entity.root 'examples', 'example'
entity.expose :name
subject.format :xml
subject.get '/example' do
c = Class.new do
attr_reader :name
def initialize(args)
@name = args[:name] || 'no name set'
end
end
present c.new(name: 'johnnyiller'), with: entity
end
get '/example'
expect(last_response).to be_successful
expect(last_response.content_type).to eq('application/xml')
expect(last_response.body).to eq <<~XML
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<example>
<name>johnnyiller</name>
</example>
</hash>
XML
end
it 'presents with json' do
entity = Class.new(Grape::Entity)
entity.root 'examples', 'example'
entity.expose :name
subject.format :json
subject.get '/example' do
c = Class.new do
attr_reader :name
def initialize(args)
@name = args[:name] || 'no name set'
end
end
present c.new(name: 'johnnyiller'), with: entity
end
get '/example'
expect(last_response).to be_successful
expect(last_response.content_type).to eq('application/json')
expect(last_response.body).to eq('{"example":{"name":"johnnyiller"}}')
end
it 'presents with jsonp utilising Rack::JSONP' do
subject.use Rack::JSONP
entity = Class.new(Grape::Entity)
entity.root 'examples', 'example'
entity.expose :name
# Rack::JSONP expects a standard JSON response in UTF-8 format
subject.format :json
subject.formatter :json, lambda { |object, _|
object.to_json.encode('utf-8')
}
subject.get '/example' do
c = Class.new do
attr_reader :name
def initialize(args)
@name = args[:name] || 'no name set'
end
end
present c.new(name: 'johnnyiller'), with: entity
end
get '/example?callback=abcDef'
expect(last_response).to be_successful
expect(last_response.content_type).to eq('application/javascript')
expect(last_response.body).to include 'abcDef({"example":{"name":"johnnyiller"}})'
end
context 'present with multiple entities' do
it 'present with multiple entities using optional symbol' do
user = Class.new do
attr_reader :name
def initialize(args)
@name = args[:name] || 'no name set'
end
end
user1 = user.new(name: 'user1')
user2 = user.new(name: 'user2')
entity = Class.new(Grape::Entity)
entity.expose :name
subject.format :json
subject.get '/example' do
present :page, 1
present :user1, user1, with: entity
present :user2, user2, with: entity
end
get '/example'
expect_response_json = {
'page' => 1,
'user1' => { 'name' => 'user1' },
'user2' => { 'name' => 'user2' }
}
expect(JSON(last_response.body)).to eq(expect_response_json)
end
end
end
describe 'Grape::Middleware::Error' do
let(:error_entity) do
Class.new(Grape::Entity) do
expose :code
expose :static
def static
'static text'
end
end
end
let(:options) { { default_message: 'Aww, hamburgers.' } }
let(:error_app) do
Class.new do
class << self
attr_accessor :error, :format
def call(_env)
throw :error, error
end
end
end
end
let(:app) do
opts = options
Rack::Builder.app do
use Spec::Support::EndpointFaker
use Grape::Middleware::Error, **opts
run ErrApp
end
end
before do
stub_const('ErrApp', error_app)
stub_const('ErrorEntity', error_entity)
end
context 'with http code' do
it 'presents an error message' do
ErrApp.error = { message: { code: 200, with: ErrorEntity } }
get '/'
expect(last_response.body).to eq({ code: 200, static: 'static text' }.to_json)
end
end
end
describe 'error_presenter' do
subject { last_response }
let(:error_presenter) do
Class.new(Grape::Entity) do
expose :code
expose :static
def static
'some static text'
end
end
end
before do
stub_const('ErrorPresenter', error_presenter)
get '/exception'
end
context 'when using http_codes' do
let(:app) do
Class.new(Grape::API) do
desc 'some desc', http_codes: [[408, 'Unauthorized', ErrorPresenter]]
get '/exception' do
error!({ code: 408 }, 408)
end
end
end
it 'is used as presenter' do
expect(subject).to be_request_timeout
expect(subject.body).to eql({ code: 408, static: 'some static text' }.to_json)
end
end
context 'when using with' do
let(:app) do
Class.new(Grape::API) do
get '/exception' do
error!({ code: 408, with: ErrorPresenter }, 408)
end
end
end
it 'presented with' do
expect(subject).to be_request_timeout
expect(subject.body).to eql({ code: 408, static: 'some static text' }.to_json)
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/integration/hashie/hashie_spec.rb | spec/integration/hashie/hashie_spec.rb | # frozen_string_literal: true
describe 'Hashie', if: defined?(Hashie) do
subject { app }
let(:app) { Class.new(Grape::API) }
describe 'Grape::ParamsBuilder::HashieMash' do
describe 'in an endpoint' do
describe '#params' do
before do
subject.params do
build_with :hashie_mash
end
subject.get do
params.class
end
end
it 'is of type Hashie::Mash' do
get '/'
expect(last_response).to be_successful
expect(last_response.body).to eq('Hashie::Mash')
end
end
end
describe 'in an api' do
before do
subject.build_with :hashie_mash
end
describe '#params' do
before do
subject.get do
params.class
end
end
it 'is Hashie::Mash' do
get '/'
expect(last_response).to be_successful
expect(last_response.body).to eq('Hashie::Mash')
end
end
context 'in a nested namespace api' do
before do
subject.namespace :foo do
get do
params.class
end
end
end
it 'is Hashie::Mash' do
get '/foo'
expect(last_response).to be_successful
expect(last_response.body).to eq('Hashie::Mash')
end
end
it 'is indifferent to key or symbol access' do
subject.params do
build_with :hashie_mash
requires :a, type: String
end
subject.get '/foo' do
[params[:a], params['a']]
end
get '/foo', a: 'bar'
expect(last_response).to be_successful
expect(last_response.body).to eq('["bar", "bar"]')
end
it 'does not overwrite route_param with a regular param if they have same name' do
subject.namespace :route_param do
route_param :foo do
get { params.to_json }
end
end
get '/route_param/bar', foo: 'baz'
expect(last_response).to be_successful
expect(last_response.body).to eq('{"foo":"bar"}')
end
it 'does not overwrite route_param with a defined regular param if they have same name' do
subject.namespace :route_param do
params do
build_with :hashie_mash
requires :foo, type: String
end
route_param :foo do
get do
[params[:foo], params['foo']]
end
end
end
get '/route_param/bar', foo: 'baz'
expect(last_response).to be_successful
expect(last_response.body).to eq('["bar", "bar"]')
end
end
end
describe 'Grape::Request' do
let(:default_method) { Rack::GET }
let(:default_params) { {} }
let(:default_options) do
{
method: method,
params: params
}
end
let(:default_env) do
Rack::MockRequest.env_for('/', options)
end
let(:method) { default_method }
let(:params) { default_params }
let(:options) { default_options }
let(:env) { default_env }
let(:request) { Grape::Request.new(env) }
describe '#params' do
let(:params) do
{
a: '123',
b: 'xyz'
}
end
it 'by default returns stringified parameter keys' do
expect(request.params).to eq(ActiveSupport::HashWithIndifferentAccess.new('a' => '123', 'b' => 'xyz'))
end
context 'when build_params_with: Grape::Extensions::Hash::ParamBuilder is specified' do
let(:request) { Grape::Request.new(env, build_params_with: :hash) }
it 'returns symbolized params' do
expect(request.params).to eq(a: '123', b: 'xyz')
end
end
describe 'with grape.routing_args' do
let(:options) do
default_options.merge('grape.routing_args' => routing_args)
end
let(:routing_args) do
{
version: '123',
route_info: '456',
c: 'ccc'
}
end
it 'cuts version and route_info' do
expect(request.params).to eq(ActiveSupport::HashWithIndifferentAccess.new(a: '123', b: 'xyz', c: 'ccc'))
end
end
end
describe 'when the build_params_with is set to Hashie' do
subject(:request_params) { Grape::Request.new(env, build_params_with: :hashie_mash).params }
context 'when the API includes a specific param builder' do
it { is_expected.to be_a(Hashie::Mash) }
end
end
end
describe 'Grape::Validations::Validators::CoerceValidator' do
context 'when params is Hashie::Mash' do
context 'for primitive collections' do
before do
subject.params do
build_with :hashie_mash
optional :a, types: [String, Array[String]]
optional :b, types: [Array[Integer], Array[String]]
optional :c, type: Array[Integer, String]
optional :d, types: [Integer, String, Set[Integer, String]]
end
subject.get '/' do
(
params.a ||
params.b ||
params.c ||
params.d
).inspect
end
end
it 'allows singular form declaration' do
get '/', a: 'one way'
expect(last_response).to be_successful
expect(last_response.body).to eq('"one way"')
get '/', a: %w[the other]
expect(last_response).to be_successful
expect(last_response.body).to eq('#<Hashie::Array ["the", "other"]>')
get '/', a: { a: 1, b: 2 }
expect(last_response).to be_bad_request
expect(last_response.body).to eq('a is invalid')
get '/', a: [1, 2, 3]
expect(last_response).to be_successful
expect(last_response.body).to eq('#<Hashie::Array ["1", "2", "3"]>')
end
it 'allows multiple collection types' do
get '/', b: [1, 2, 3]
expect(last_response).to be_successful
expect(last_response.body).to eq('#<Hashie::Array [1, 2, 3]>')
get '/', b: %w[1 2 3]
expect(last_response).to be_successful
expect(last_response.body).to eq('#<Hashie::Array [1, 2, 3]>')
get '/', b: [1, true, 'three']
expect(last_response).to be_successful
expect(last_response.body).to eq('#<Hashie::Array ["1", "true", "three"]>')
end
it 'allows collections with multiple types' do
get '/', c: [1, '2', true, 'three']
expect(last_response).to be_successful
expect(last_response.body).to eq('#<Hashie::Array [1, 2, "true", "three"]>')
get '/', d: '1'
expect(last_response).to be_successful
expect(last_response.body).to eq('1')
get '/', d: 'one'
expect(last_response).to be_successful
expect(last_response.body).to eq('"one"')
get '/', d: %w[1 two]
expect(last_response).to be_successful
json_set = JSON.parse([1, 'two'].to_set.to_json)
expect(last_response.body).to eq(json_set)
end
end
end
end
describe 'Grape::Endpoint' do
before do
subject.format :json
subject.params do
requires :first
optional :second
optional :third, default: 'third-default'
optional :multiple_types, types: [Integer, String]
optional :nested, type: Hash do
optional :fourth
optional :fifth
optional :nested_two, type: Hash do
optional :sixth
optional :nested_three, type: Hash do
optional :seventh
end
end
optional :nested_arr, type: Array do
optional :eighth
end
optional :empty_arr, type: Array
optional :empty_typed_arr, type: Array[String]
optional :empty_hash, type: Hash
optional :empty_set, type: Set
optional :empty_typed_set, type: Set[String]
end
optional :arr, type: Array do
optional :nineth
end
optional :empty_arr, type: Array
optional :empty_typed_arr, type: Array[String]
optional :empty_hash, type: Hash
optional :empty_hash_two, type: Hash
optional :empty_set, type: Set
optional :empty_typed_set, type: Set[String]
end
end
context 'when params are not built with default class' do
it 'returns an object that corresponds with the params class - hashie mash' do
subject.params do
build_with :hashie_mash
end
subject.get '/declared' do
d = declared(params, include_missing: true)
{ declared_class: d.class.to_s }
end
get '/declared?first=present'
expect(JSON.parse(last_response.body)['declared_class']).to eq('Hashie::Mash')
end
end
end
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/integration/multi_xml/xml_spec.rb | spec/integration/multi_xml/xml_spec.rb | # frozen_string_literal: true
describe Grape::Xml, if: defined?(MultiXml) do
subject { described_class }
it { is_expected.to eq(MultiXml) }
end
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | false |
ruby-grape/grape | https://github.com/ruby-grape/grape/blob/17fb0cf64296e9c9c968ea7b62f7614538070be4/spec/grape/endpoint_spec.rb | spec/grape/endpoint_spec.rb | # frozen_string_literal: true
describe Grape::Endpoint do
subject { Class.new(Grape::API) }
def app
subject
end
describe '.before_each' do
after { described_class.before_each.clear }
it 'is settable via block' do
block = ->(_endpoint) { 'noop' }
described_class.before_each(&block)
expect(described_class.before_each.first).to eq(block)
end
it 'is settable via reference' do
block = ->(_endpoint) { 'noop' }
described_class.before_each block
expect(described_class.before_each.first).to eq(block)
end
it 'is able to override a helper' do
subject.get('/') { current_user }
expect { get '/' }.to raise_error(NameError)
described_class.before_each do |endpoint|
allow(endpoint).to receive(:current_user).and_return('Bob')
end
get '/'
expect(last_response.body).to eq('Bob')
described_class.before_each(nil)
expect { get '/' }.to raise_error(NameError)
end
it 'is able to stack helper' do
subject.get('/') do
authenticate_user!
current_user
end
expect { get '/' }.to raise_error(NameError)
described_class.before_each do |endpoint|
allow(endpoint).to receive(:current_user).and_return('Bob')
end
described_class.before_each do |endpoint|
allow(endpoint).to receive(:authenticate_user!).and_return(true)
end
get '/'
expect(last_response.body).to eq('Bob')
described_class.before_each(nil)
expect { get '/' }.to raise_error(NameError)
end
end
it 'sets itself in the env upon call' do
subject.get('/') { 'Hello world.' }
get '/'
expect(last_request.env[Grape::Env::API_ENDPOINT]).to be_a(described_class)
end
describe '#status' do
it 'is callable from within a block' do
subject.get('/home') do
status 206
'Hello'
end
get '/home'
expect(last_response.status).to eq(206)
expect(last_response.body).to eq('Hello')
end
it 'is set as default to 200 for get' do
memoized_status = nil
subject.get('/home') do
memoized_status = status
'Hello'
end
get '/home'
expect(last_response.status).to eq(200)
expect(memoized_status).to eq(200)
expect(last_response.body).to eq('Hello')
end
it 'is set as default to 201 for post' do
memoized_status = nil
subject.post('/home') do
memoized_status = status
'Hello'
end
post '/home'
expect(last_response.status).to eq(201)
expect(memoized_status).to eq(201)
expect(last_response.body).to eq('Hello')
end
context 'when rescue_from' do
subject { last_request.env[Grape::Env::API_ENDPOINT].status }
before do
post '/'
end
context 'when :all blockless' do
context 'when default_error_status is not set' do
let(:app) do
Class.new(Grape::API) do
rescue_from :all
post { raise StandardError }
end
end
it { is_expected.to eq(last_response.status) }
end
context 'when default_error_status is set' do
let(:app) do
Class.new(Grape::API) do
default_error_status 418
rescue_from :all
post { raise StandardError }
end
end
it { is_expected.to eq(last_response.status) }
end
end
context 'when :with' do
let(:app) do
Class.new(Grape::API) do
helpers do
def handle_argument_error
error!("I'm a teapot!", 418)
end
end
rescue_from ArgumentError, with: :handle_argument_error
post { raise ArgumentError }
end
end
it { is_expected.to eq(last_response.status) }
end
end
end
describe '#header' do
it 'is callable from within a block' do
subject.get('/hey') do
header 'X-Awesome', 'true'
'Awesome'
end
get '/hey'
expect(last_response.headers['X-Awesome']).to eq('true')
end
end
describe '#headers' do
before do
subject.get('/headers') do
headers.to_json
end
end
let(:headers) do
Grape::Util::Header.new.tap do |h|
h['Cookie'] = ''
h['Host'] = 'example.org'
end
end
it 'includes request headers' do
get '/headers'
expect(JSON.parse(last_response.body)).to include(headers.to_h)
end
it 'includes additional request headers' do
get '/headers', nil, 'HTTP_X_GRAPE_CLIENT' => '1'
x_grape_client_header = 'x-grape-client'
expect(JSON.parse(last_response.body)[x_grape_client_header]).to eq('1')
end
end
describe '#cookies' do
it 'is callable from within a block' do
subject.get('/get/cookies') do
cookies['my-awesome-cookie1'] = 'is cool'
cookies['my-awesome-cookie2'] = {
value: 'is cool too',
domain: 'my.example.com',
path: '/',
secure: true
}
cookies[:cookie3] = 'symbol'
cookies['cookie4'] = 'secret code here'
end
get('/get/cookies')
expect(last_response.cookie_jar).to contain_exactly(
{ 'name' => 'cookie3', 'value' => 'symbol' },
{ 'name' => 'cookie4', 'value' => 'secret code here' },
{ 'name' => 'my-awesome-cookie1', 'value' => 'is cool' },
{ 'name' => 'my-awesome-cookie2', 'value' => 'is cool too', 'domain' => 'my.example.com', 'path' => '/', 'secure' => true }
)
end
it 'sets browser cookies and does not set response cookies' do
set_cookie %w[username=mrplum sandbox=true]
subject.get('/username') do
cookies[:username]
end
get '/username'
expect(last_response.body).to eq('mrplum')
expect(last_response.cookie_jar).to be_empty
end
it 'sets and update browser cookies' do
set_cookie %w[username=user sandbox=false]
subject.get('/username') do
cookies[:sandbox] = true if cookies[:sandbox] == 'false'
cookies[:username] += '_test'
end
get '/username'
expect(last_response.body).to eq('user_test')
expect(last_response.cookie_jar).to contain_exactly(
{ 'name' => 'sandbox', 'value' => 'true' },
{ 'name' => 'username', 'value' => 'user_test' }
)
end
it 'deletes cookie' do
set_cookie %w[delete_this_cookie=1 and_this=2]
subject.get('/test') do
sum = 0
cookies.each do |name, val|
sum += val.to_i
cookies.delete name
end
sum
end
get '/test'
expect(last_response.body).to eq('3')
expect(last_response.cookie_jar).to contain_exactly(
{ 'name' => 'and_this', 'value' => '', 'max-age' => 0, 'expires' => Time.at(0) },
{ 'name' => 'delete_this_cookie', 'value' => '', 'max-age' => 0, 'expires' => Time.at(0) }
)
end
it 'deletes cookies with path' do
set_cookie %w[delete_this_cookie=1 and_this=2]
subject.get('/test') do
sum = 0
cookies.each do |name, val|
sum += val.to_i
cookies.delete name, path: '/test'
end
sum
end
get '/test'
expect(last_response.body).to eq('3')
expect(last_response.cookie_jar).to contain_exactly(
{ 'name' => 'and_this', 'path' => '/test', 'value' => '', 'max-age' => 0, 'expires' => Time.at(0) },
{ 'name' => 'delete_this_cookie', 'path' => '/test', 'value' => '', 'max-age' => 0, 'expires' => Time.at(0) }
)
end
end
describe '#params' do
context 'default class' do
it 'is a ActiveSupport::HashWithIndifferentAccess' do
subject.get '/foo' do
params.class
end
get '/foo'
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('ActiveSupport::HashWithIndifferentAccess')
end
end
context 'sets a value to params' do
it 'params' do
subject.params do
requires :a, type: String
end
subject.get '/foo' do
params[:a] = 'bar'
end
get '/foo', a: 'foo'
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('bar')
end
end
end
describe '#params' do
it 'is available to the caller' do
subject.get('/hey') do
params[:howdy]
end
get '/hey?howdy=hey'
expect(last_response.body).to eq('hey')
end
it 'parses from path segments' do
subject.get('/hey/:id') do
params[:id]
end
get '/hey/12'
expect(last_response.body).to eq('12')
end
it 'deeply converts nested params' do
subject.get '/location' do
params[:location][:city]
end
get '/location?location[city]=Dallas'
expect(last_response.body).to eq('Dallas')
end
context 'with special requirements' do
it 'parses email param with provided requirements for params' do
subject.get('/:person_email', requirements: { person_email: /.*/ }) do
params[:person_email]
end
get '/someone@example.com'
expect(last_response.body).to eq('someone@example.com')
get 'someone@example.com.pl'
expect(last_response.body).to eq('someone@example.com.pl')
end
it 'parses many params with provided regexps' do
subject.get('/:person_email/test/:number', requirements: { person_email: /someone@(.*).com/, number: /[0-9]/ }) do
params[:person_email] << params[:number]
end
get '/someone@example.com/test/1'
expect(last_response.body).to eq('someone@example.com1')
get '/someone@testing.wrong/test/1'
expect(last_response.status).to eq(404)
get 'someone@test.com/test/wrong_number'
expect(last_response.status).to eq(404)
get 'someone@test.com/wrong_middle/1'
expect(last_response.status).to eq(404)
end
context 'namespace requirements' do
before do
subject.namespace :outer, requirements: { person_email: /abc@(.*).com/ } do
get('/:person_email') do
params[:person_email]
end
namespace :inner, requirements: { number: /[0-9]/, person_email: /someone@(.*).com/ } do
get '/:person_email/test/:number' do
params[:person_email] << params[:number]
end
end
end
end
it 'parse email param with provided requirements for params' do
get '/outer/abc@example.com'
expect(last_response.body).to eq('abc@example.com')
end
it "overrides outer namespace's requirements" do
get '/outer/inner/someone@testing.wrong/test/1'
expect(last_response.status).to eq(404)
get '/outer/inner/someone@testing.com/test/1'
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('someone@testing.com1')
end
end
end
context 'from body parameters' do
before do
subject.post '/request_body' do
params[:user]
end
subject.put '/request_body' do
params[:user]
end
end
it 'converts JSON bodies to params' do
post '/request_body', Grape::Json.dump(user: 'Bobby T.'), 'CONTENT_TYPE' => 'application/json'
expect(last_response.body).to eq('Bobby T.')
end
it 'does not convert empty JSON bodies to params' do
put '/request_body', '', 'CONTENT_TYPE' => 'application/json'
expect(last_response.body).to eq('')
end
if Object.const_defined? :MultiXml
it 'converts XML bodies to params' do
post '/request_body', '<user>Bobby T.</user>', 'CONTENT_TYPE' => 'application/xml'
expect(last_response.body).to eq('Bobby T.')
end
it 'converts XML bodies to params' do
put '/request_body', '<user>Bobby T.</user>', 'CONTENT_TYPE' => 'application/xml'
expect(last_response.body).to eq('Bobby T.')
end
else
let(:body) { '<user>Bobby T.</user>' }
it 'converts XML bodies to params' do
post '/request_body', body, 'CONTENT_TYPE' => 'application/xml'
expect(last_response.body).to eq(Grape::Xml.parse(body)['user'].to_s)
end
it 'converts XML bodies to params' do
put '/request_body', body, 'CONTENT_TYPE' => 'application/xml'
expect(last_response.body).to eq(Grape::Xml.parse(body)['user'].to_s)
end
end
it 'does not include parameters not defined by the body' do
subject.post '/omitted_params' do
error! 400, 'expected nil' if params[:version]
params[:user]
end
post '/omitted_params', Grape::Json.dump(user: 'Bob'), 'CONTENT_TYPE' => 'application/json'
expect(last_response.status).to eq(201)
expect(last_response.body).to eq('Bob')
end
# Rack swallowed this error until v2.2.0
it 'returns a 400 if given an invalid multipart body', if: Gem::Version.new(Rack.release) >= Gem::Version.new('2.2.0') do
subject.params do
requires :file, type: Rack::Multipart::UploadedFile
end
subject.post '/upload' do
params[:file][:filename]
end
post '/upload', { file: '' }, 'CONTENT_TYPE' => 'multipart/form-data; boundary=foobar'
expect(last_response.status).to eq(400)
expect(last_response.body).to eq('file is invalid')
end
end
context 'when the limit on multipart files is exceeded' do
around do |example|
limit = Rack::Utils.multipart_part_limit
Rack::Utils.multipart_part_limit = 1
example.run
Rack::Utils.multipart_part_limit = limit
end
it 'returns a 413 if given too many multipart files' do
subject.params do
requires :file, type: Rack::Multipart::UploadedFile
end
subject.post '/upload' do
params[:file][:filename]
end
post '/upload', { file: Rack::Test::UploadedFile.new(__FILE__, 'text/plain'), extra: Rack::Test::UploadedFile.new(__FILE__, 'text/plain') }
expect(last_response.status).to eq(413)
expect(last_response.body).to eq("the number of uploaded files exceeded the system's configured limit (1)")
end
end
it 'responds with a 415 for an unsupported content-type' do
subject.format :json
# subject.content_type :json, "application/json"
subject.put '/request_body' do
params[:user]
end
put '/request_body', '<user>Bobby T.</user>', 'CONTENT_TYPE' => 'application/xml'
expect(last_response.status).to eq(415)
expect(last_response.body).to eq('{"error":"The provided content-type \'application/xml\' is not supported."}')
end
it 'does not accept text/plain in JSON format if application/json is specified as content type' do
subject.format :json
subject.default_format :json
subject.put '/request_body' do
params[:user]
end
put '/request_body', Grape::Json.dump(user: 'Bob'), 'CONTENT_TYPE' => 'text/plain'
expect(last_response.status).to eq(415)
expect(last_response.body).to eq('{"error":"The provided content-type \'text/plain\' is not supported."}')
end
context 'content type with params' do
before do
subject.format :json
subject.content_type :json, 'application/json; charset=utf-8'
subject.post do
params[:data]
end
post '/', Grape::Json.dump(data: { some: 'payload' }), 'CONTENT_TYPE' => 'application/json'
end
it 'does not response with 406 for same type without params' do
expect(last_response.status).not_to be 406
end
it 'responses with given content type in headers' do
expect(last_response.content_type).to eq 'application/json; charset=utf-8'
end
end
context 'precedence' do
before do
subject.format :json
subject.namespace '/:id' do
get do
{
params: params[:id]
}
end
post do
{
params: params[:id]
}
end
put do
{
params: params[:id]
}
end
end
end
it 'route string params have higher precedence than body params' do
post '/123', { id: 456 }.to_json
expect(JSON.parse(last_response.body)['params']).to eq '123'
put '/123', { id: 456 }.to_json
expect(JSON.parse(last_response.body)['params']).to eq '123'
end
it 'route string params have higher precedence than URL params' do
get '/123?id=456'
expect(JSON.parse(last_response.body)['params']).to eq '123'
post '/123?id=456'
expect(JSON.parse(last_response.body)['params']).to eq '123'
end
end
context 'sets a value to params' do
it 'params' do
subject.params do
requires :a, type: String
end
subject.get '/foo' do
params[:a] = 'bar'
end
get '/foo', a: 'foo'
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('bar')
end
end
end
describe '#error!' do
it 'accepts a message' do
subject.get('/hey') do
error! 'This is not valid.'
'This is valid.'
end
get '/hey'
expect(last_response.status).to eq(500)
expect(last_response.body).to eq('This is not valid.')
end
it 'accepts a code' do
subject.desc 'patate' do
http_codes [[401, 'Unauthorized']]
end
subject.get('/hey') do
error! 'Unauthorized.', 401
end
get '/hey'
expect(last_response.status).to eq(401)
expect(last_response.body).to eq('Unauthorized.')
end
it 'accepts an object and render it in format' do
subject.get '/hey' do
error!({ 'dude' => 'rad' }, 403)
end
get '/hey.json'
expect(last_response.status).to eq(403)
expect(last_response.body).to eq('{"dude":"rad"}')
end
it 'accepts a frozen object' do
subject.get '/hey' do
error!({ 'dude' => 'rad' }.freeze, 403)
end
get '/hey.json'
expect(last_response.status).to eq(403)
expect(last_response.body).to eq('{"dude":"rad"}')
end
it 'can specifiy headers' do
subject.get '/hey' do
error!({ 'dude' => 'rad' }, 403, 'X-Custom' => 'value')
end
get '/hey.json'
expect(last_response.status).to eq(403)
expect(last_response.headers['X-Custom']).to eq('value')
end
it 'merges additional headers with headers set before call' do
subject.before do
header 'X-Before-Test', 'before-sample'
end
subject.get '/hey' do
header 'X-Test', 'test-sample'
error!({ 'dude' => 'rad' }, 403, 'X-Error' => 'error')
end
get '/hey.json'
expect(last_response.headers['X-Before-Test']).to eq('before-sample')
expect(last_response.headers['X-Test']).to eq('test-sample')
expect(last_response.headers['X-Error']).to eq('error')
end
it 'does not merges additional headers with headers set after call' do
subject.after do
header 'X-After-Test', 'after-sample'
end
subject.get '/hey' do
error!({ 'dude' => 'rad' }, 403, 'X-Error' => 'error')
end
get '/hey.json'
expect(last_response.headers['X-Error']).to eq('error')
expect(last_response.headers['X-After-Test']).to be_nil
end
it 'sets the status code for the endpoint' do
memoized_endpoint = nil
subject.get '/hey' do
memoized_endpoint = self
error!({ 'dude' => 'rad' }, 403, 'X-Custom' => 'value')
end
get '/hey.json'
expect(memoized_endpoint.status).to eq(403)
end
end
describe '#redirect' do
it 'redirects to a url with status 302' do
subject.get('/hey') do
redirect '/ha'
end
get '/hey'
expect(last_response.status).to eq 302
expect(last_response.location).to eq '/ha'
expect(last_response.body).to eq 'This resource has been moved temporarily to /ha.'
end
it 'has status code 303 if it is not get request and it is http 1.1' do
subject.post('/hey') do
redirect '/ha'
end
post '/hey', {}, 'HTTP_VERSION' => 'HTTP/1.1', 'SERVER_PROTOCOL' => 'HTTP/1.1'
expect(last_response.status).to eq 303
expect(last_response.location).to eq '/ha'
expect(last_response.body).to eq 'An alternate resource is located at /ha.'
end
it 'support permanent redirect' do
subject.get('/hey') do
redirect '/ha', permanent: true
end
get '/hey'
expect(last_response.status).to eq 301
expect(last_response.location).to eq '/ha'
expect(last_response.body).to eq 'This resource has been moved permanently to /ha.'
end
it 'allows for an optional redirect body override' do
subject.get('/hey') do
redirect '/ha', body: 'test body'
end
get '/hey'
expect(last_response.body).to eq 'test body'
end
end
describe 'NameError' do
context 'when referencing an undefined local variable or method' do
it 'raises NameError but stripping the internals of the Grape::Endpoint class and including the API route' do
subject.get('/hey') { undefined_helper }
expect { get '/hey' }.to raise_error(NameError, /^undefined local variable or method ['`]undefined_helper' for/)
end
end
end
it 'does not persist params between calls' do
subject.post('/new') do
params[:text]
end
post '/new', text: 'abc'
expect(last_response.body).to eq('abc')
post '/new', text: 'def'
expect(last_response.body).to eq('def')
end
it 'resets all instance variables (except block) between calls' do
subject.helpers do
def memoized
@memoized ||= params[:howdy]
end
end
subject.get('/hello') do
memoized
end
get '/hello?howdy=hey'
expect(last_response.body).to eq('hey')
get '/hello?howdy=yo'
expect(last_response.body).to eq('yo')
end
context 'when calling return' do
it 'does not raise a LocalJumpError' do
subject.get('/home') do
return 'Hello'
end
get '/home'
expect(last_response.status).to eq(200)
expect(last_response.body).to eq('Hello')
end
end
context 'filters' do
describe 'before filters' do
it 'runs the before filter if set' do
subject.before { env['before_test'] = 'OK' }
subject.get('/before_test') { env['before_test'] }
get '/before_test'
expect(last_response.body).to eq('OK')
end
end
describe 'after filters' do
it 'overrides the response body if it sets it' do
subject.after { body 'after' }
subject.get('/after_test') { 'during' }
get '/after_test'
expect(last_response.body).to eq('after')
end
it 'does not override the response body with its return' do
subject.after { 'after' }
subject.get('/after_test') { 'body' }
get '/after_test'
expect(last_response.body).to eq('body')
end
end
it 'allows adding to response with present' do
subject.format :json
subject.before { present :before, 'before' }
subject.before_validation { present :before_validation, 'before_validation' }
subject.after_validation { present :after_validation, 'after_validation' }
subject.after { present :after, 'after' }
subject.get :all_filters do
present :endpoint, 'endpoint'
end
get '/all_filters'
json = JSON.parse(last_response.body)
expect(json.keys).to match_array %w[before before_validation after_validation endpoint after]
end
context 'when terminating the response with error!' do
it 'breaks normal call chain' do
called = []
subject.before { called << 'before' }
subject.before_validation { called << 'before_validation' }
subject.after_validation { error! :oops, 500 }
subject.after { called << 'after' }
subject.get :error_filters do
called << 'endpoint'
''
end
get '/error_filters'
expect(last_response.status).to be 500
expect(called).to match_array %w[before before_validation]
end
it 'allows prior and parent filters of same type to run' do
called = []
subject.before { called << 'parent' }
subject.namespace :parent do
before { called << 'prior' }
before { error! :oops, 500 }
before { called << 'subsequent' }
get :hello do
called << :endpoint
'Hello!'
end
end
get '/parent/hello'
expect(last_response.status).to be 500
expect(called).to match_array %w[parent prior]
end
end
end
context 'anchoring' do
describe 'delete 204' do
it 'allows for the anchoring option with a delete method' do
subject.delete('/example', anchor: true)
delete '/example/and/some/more'
expect(last_response).to be_not_found
end
it 'anchors paths by default for the delete method' do
subject.delete '/example'
delete '/example/and/some/more'
expect(last_response).to be_not_found
end
it 'responds to /example/and/some/more for the non-anchored delete method' do
subject.delete '/example', anchor: false
delete '/example/and/some/more'
expect(last_response).to be_no_content
expect(last_response.body).to be_empty
end
end
describe 'delete 200, with response body' do
it 'responds to /example/and/some/more for the non-anchored delete method' do
subject.delete('/example', anchor: false) do
status 200
body 'deleted'
end
delete '/example/and/some/more'
expect(last_response).to be_successful
expect(last_response.body).not_to be_empty
end
end
describe 'delete 200, with a return value (no explicit body)' do
it 'responds to /example delete method' do
subject.delete(:example) { 'deleted' }
delete '/example'
expect(last_response.status).to be 200
expect(last_response.body).not_to be_empty
end
end
describe 'delete 204, with nil has return value (no explicit body)' do
it 'responds to /example delete method' do
subject.delete(:example) { nil }
delete '/example'
expect(last_response.status).to be 204
expect(last_response.body).to be_empty
end
end
describe 'delete 204, with empty array has return value (no explicit body)' do
it 'responds to /example delete method' do
subject.delete(:example) { '' }
delete '/example'
expect(last_response.status).to be 204
expect(last_response.body).to be_empty
end
end
describe 'all other' do
%w[post get head put options patch].each do |verb|
it "allows for the anchoring option with a #{verb.upcase} method" do
subject.__send__(verb, '/example', anchor: true) do
verb
end
__send__(verb, '/example/and/some/more')
expect(last_response.status).to be 404
end
it "anchors paths by default for the #{verb.upcase} method" do
subject.__send__(verb, '/example') do
verb
end
__send__(verb, '/example/and/some/more')
expect(last_response.status).to be 404
end
it "responds to /example/and/some/more for the non-anchored #{verb.upcase} method" do
subject.__send__(verb, '/example', anchor: false) do
verb
end
__send__(verb, '/example/and/some/more')
expect(last_response.status).to eql verb == 'post' ? 201 : 200
expect(last_response.body).to eql verb == 'head' ? '' : verb
end
end
end
end
context 'request' do
it 'is set to the url requested' do
subject.get('/url') do
request.url
end
get '/url'
expect(last_response.body).to eq('http://example.org/url')
end
['v1', :v1].each do |version|
it "includes version #{version}" do
subject.version version, using: :path
subject.get('/url') do
request.url
end
get "/#{version}/url"
expect(last_response.body).to eq("http://example.org/#{version}/url")
end
end
it 'includes prefix' do
subject.version 'v1', using: :path
subject.prefix 'api'
subject.get('/url') do
request.url
end
get '/api/v1/url'
expect(last_response.body).to eq('http://example.org/api/v1/url')
end
end
context 'version headers' do
before do
# NOTE: a 404 is returned instead of the 406 if cascade: false is not set.
subject.version 'v1', using: :header, vendor: 'ohanapi', cascade: false
subject.get '/test' do
'Hello!'
end
end
it 'result in a 406 response if they are invalid' do
get '/test', {}, 'HTTP_ACCEPT' => 'application/vnd.ohanapi.v1+json'
expect(last_response.status).to eq(406)
end
it 'result in a 406 response if they cannot be parsed' do
get '/test', {}, 'HTTP_ACCEPT' => 'application/vnd.ohanapi.v1+json; version=1'
expect(last_response.status).to eq(406)
end
end
context 'binary' do
before do
subject.get do
stream FileStreamer.new(__FILE__)
end
end
it 'suports stream objects in response' do
get '/'
expect(last_response.status).to eq 200
expect(last_response.body).to eq File.read(__FILE__)
end
end
context 'validation errors' do
before do
subject.before do
header['Access-Control-Allow-Origin'] = '*'
end
subject.params do
requires :id, type: String
end
subject.get do
'should not get here'
end
end
it 'returns the errors, and passes headers' do
get '/'
expect(last_response.status).to eq 400
expect(last_response.body).to eq 'id is missing'
expect(last_response.headers['Access-Control-Allow-Origin']).to eq('*')
end
end
context 'instrumentation' do
before do
subject.before do
# Placeholder
end
subject.get do
'hello'
end
@events = []
@subscriber = ActiveSupport::Notifications.subscribe(/grape/) do |*args|
@events << ActiveSupport::Notifications::Event.new(*args)
end
end
after do
ActiveSupport::Notifications.unsubscribe(@subscriber)
end
it 'notifies AS::N' do
get '/'
# In order that the events finalized (time each block ended)
expect(@events).to contain_exactly(
have_attributes(name: 'endpoint_run_filters.grape', payload: { endpoint: a_kind_of(described_class),
filters: a_collection_containing_exactly(an_instance_of(Proc)),
type: :before }),
have_attributes(name: 'endpoint_run_filters.grape', payload: { endpoint: a_kind_of(described_class),
filters: [],
type: :before_validation }),
have_attributes(name: 'endpoint_run_validators.grape', payload: { endpoint: a_kind_of(described_class),
validators: [],
request: a_kind_of(Grape::Request) }),
have_attributes(name: 'endpoint_run_filters.grape', payload: { endpoint: a_kind_of(described_class),
filters: [],
type: :after_validation }),
have_attributes(name: 'endpoint_render.grape', payload: { endpoint: a_kind_of(described_class) }),
have_attributes(name: 'endpoint_run_filters.grape', payload: { endpoint: a_kind_of(described_class),
| ruby | MIT | 17fb0cf64296e9c9c968ea7b62f7614538070be4 | 2026-01-04T15:38:22.454413Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.