Class: RuboCop::Cop::Gusto::UsePaintNotColorize

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/gusto/use_paint_not_colorize.rb

Overview

Requires the use of the ‘paint` gem for terminal color methods on strings

Examples:


# bad
"string".cyan
"string".red
"string".green
str = "hello"
str.cyan
"string".colorize(:blue)
"string".colorize(:color => :blue)
"string".colorize(:color => :blue, :background => :red)
"string".blue.on_red
"string".colorize(:blue).on_red
"string".blue.underline

# good
"string"

# if color is needed, use `paint` gem
Paint["string", :cyan]
Paint["string", :red]
Paint["string", :green]
Paint[str, :cyan]
Paint["string", :blue]
Paint["string", :blue, :red]

Constant Summary collapse

COLOR_METHODS =

Common terminal color methods that should be prevented

Set.new(
  %i(
    black
    red
    green
    yellow
    blue
    magenta
    cyan
    white
    light_black
    light_red
    light_green
    light_yellow
    light_blue
    light_magenta
    light_cyan
    light_white
    colorize
    on_black
    on_red
    on_green
    on_yellow
    on_blue
    on_magenta
    on_cyan
    on_white
    on_light_black
    on_light_red
    on_light_green
    on_light_yellow
    on_light_blue
    on_light_magenta
    on_light_cyan
    on_light_white
    bold
    italic
    underline
    blink
    swap
    hide
    uncolorize
  )
).freeze
STYLE_MODIFIERS =

Style modifiers that are applied as additional options in Paint

Set.new(
  %i(
    bold
    italic
    underline
    blink
    swap
    hide
  )
).freeze
MSG =
"Use Paint instead of colorize for terminal colors."
PROHIBITED_CLASS =
"String"
RESTRICT_ON_SEND =
COLOR_METHODS

Instance Method Summary collapse

Instance Method Details

#on_csend(node) ⇒ Object



114
115
116
117
118
# File 'lib/rubocop/cop/gusto/use_paint_not_colorize.rb', line 114

def on_csend(node)
  return unless string_or_colorized_receiver?(node.receiver)

  add_offense(node) # no autocorrection for safe navigation due to chained calls
end

#on_send(node) ⇒ Object



105
106
107
108
109
110
111
112
# File 'lib/rubocop/cop/gusto/use_paint_not_colorize.rb', line 105

def on_send(node)
  return unless node.receiver
  return unless string_or_colorized_receiver?(node.receiver)

  add_offense(node) do |corrector|
    corrector.replace(node, correction(node))
  end
end