Class: Ducalis::RegexCop

Inherits:
RuboCop::Cop::Cop
  • Object
show all
Includes:
RuboCop::Cop::DefNode
Defined in:
lib/ducalis/cops/regex_cop.rb

Constant Summary collapse

OFFENSE =
<<-MESSAGE.gsub(/^ +\|\s/, '').strip
  | It's better to move regex to constants with example instead of direct using it. It will allow you to reuse this regex and provide instructions for others.

  | Example:

  | ```ruby
  | CONST_NAME = %<constant>s # "%<example>s"
  | %<fixed_string>s
  | ```

MESSAGE
SELF_DESCRIPTIVE =
%w(
  /[[:alnum:]]/
  /[[:alpha:]]/
  /[[:blank:]]/
  /[[:cntrl:]]/
  /[[:digit:]]/
  /[[:graph:]]/
  /[[:lower:]]/
  /[[:print:]]/
  /[[:punct:]]/
  /[[:space:]]/
  /[[:upper:]]/
  /[[:xdigit:]]/
  /[[:word:]]/
  /[[:ascii:]]/
).freeze
DETAILS =
"Available regexes are:
#{SELF_DESCRIPTIVE.map { |name| "`#{name}`" }.join(', ')}".freeze
DEFAULT_EXAMPLE =
'some_example'.freeze

Instance Method Summary collapse

Instance Method Details

#on_begin(node) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/ducalis/cops/regex_cop.rb', line 44

def on_begin(node)
  not_defined_regexes(node).each do |regex|
    next if SELF_DESCRIPTIVE.include?(regex.source) || const_dynamic?(regex)

    add_offense(regex, :expression, format(OFFENSE, present_node(regex)))
  end
end