Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Created July 10, 2024 14:20
Show Gist options
  • Save glaucocustodio/ccdb105ec97517728b8eac39177ebbc5 to your computer and use it in GitHub Desktop.
Save glaucocustodio/ccdb105ec97517728b8eac39177ebbc5 to your computer and use it in GitHub Desktop.
custom rubocop cop for checking if variable names are too short
# frozen_string_literal: true
# put this file at .rubocop/cop/naming/short_variable_name.rb
# then ensure you have the following in .rubocop.yml:
#
# require:
# - .rubocop/cop/naming/short_variable_name.rb
#
# Naming/ShortVariableName:
# Enabled: true
# Exclude:
# - 'config/initializers/**/*'
# - 'lib/tasks/**/*'
# - 'db/**/*'
# - 'bin/**/*'
module RuboCop
module Cop
module Naming
# This cop checks for variable names that are too short.
# By default, it requires variable names to be at least 3 characters long.
# The minimum length and exceptions can be configured.
# The cop also allows for certain short variable names by default: `i` and `id`.
#
# @example
# # bad
# in = 0
# us = 0
#
# # good
# index = 0
# user = 0
#
class ShortVariableName < Base
include AllowedIdentifiers
include ConfigurableNaming
include AllowedPattern
exclude_limit "Min"
MSG = "Variable name `%<variable_name>s` is too short (must be at least %<min>d chars long)."
def on_lvasgn(node)
name, = *node
return unless name
return if name.length >= min
return if name.to_s.start_with?("_")
return if exceptions.include?(name.to_s)
add_offense(node.loc.name, message: message(name))
end
alias_method :on_ivasgn, :on_lvasgn
alias_method :on_cvasgn, :on_lvasgn
alias_method :on_arg, :on_lvasgn
alias_method :on_optarg, :on_lvasgn
alias_method :on_restarg, :on_lvasgn
alias_method :on_kwoptarg, :on_lvasgn
alias_method :on_kwarg, :on_lvasgn
alias_method :on_kwrestarg, :on_lvasgn
alias_method :on_blockarg, :on_lvasgn
alias_method :on_lvar, :on_lvasgn
private
def message(variable_name)
format(MSG, variable_name: variable_name, min: min)
end
def min
cop_config.fetch("Min", 3)
end
def exceptions
Array(cop_config["Exceptions"]).presence || ["i", "id"]
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment