Class: RuboCop::Cop::Utils::FormatString

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/cop/utils/format_string.rb

Overview

Parses Kernel#sprintf format strings.

Defined Under Namespace

Classes: FormatSequence

Constant Summary collapse

DIGIT_DOLLAR =

Escaping the ‘#` in `INTERPOLATION` and `TEMPLATE_NAME` is necessary to avoid a bug in Ruby 3.2.0 See: bugs.ruby-lang.org/issues/19379

/(?<arg_number>\d+)\$/.freeze
INTERPOLATION =
/\#\{.*?\}/.freeze
FLAG =
/[ #0+-]|#{DIGIT_DOLLAR}/.freeze
NUMBER_ARG =
/\*#{DIGIT_DOLLAR}?/.freeze
NUMBER =
/\d+|#{NUMBER_ARG}|#{INTERPOLATION}/.freeze
WIDTH =
/(?<width>#{NUMBER})/.freeze
PRECISION =
/\.(?<precision>#{NUMBER}?)/.freeze
TYPE =
/(?<type>[bBdiouxXeEfgGaAcps])/.freeze
NAME =
/<(?<name>\w+)>/.freeze
TEMPLATE_NAME =
/(?<!\#)\{(?<name>\w+)\}/.freeze
SEQUENCE =
/
    % (?<type>%)
  | % (?<flags>#{FLAG}*)
    (?:
      (?: #{WIDTH}? #{PRECISION}? #{NAME}?
        | #{WIDTH}? #{NAME} #{PRECISION}?
        | #{NAME} (?<more_flags>#{FLAG}*) #{WIDTH}? #{PRECISION}?
      ) #{TYPE}
      | #{WIDTH}? #{PRECISION}? #{TEMPLATE_NAME}
    )
/x.freeze

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ FormatString

Returns a new instance of FormatString.



104
105
106
# File 'lib/rubocop/cop/utils/format_string.rb', line 104

def initialize(string)
  @source = string
end

Instance Method Details

#format_sequencesObject



108
109
110
# File 'lib/rubocop/cop/utils/format_string.rb', line 108

def format_sequences
  @format_sequences ||= parse
end

#max_digit_dollar_numObject



120
121
122
# File 'lib/rubocop/cop/utils/format_string.rb', line 120

def max_digit_dollar_num
  format_sequences.map(&:max_digit_dollar_num).max
end

#named_interpolation?Boolean

Returns:

  • (Boolean)


116
117
118
# File 'lib/rubocop/cop/utils/format_string.rb', line 116

def named_interpolation?
  format_sequences.any?(&:name)
end

#valid?Boolean

Returns:

  • (Boolean)


112
113
114
# File 'lib/rubocop/cop/utils/format_string.rb', line 112

def valid?
  !mixed_formats?
end