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.



94
95
96
# File 'lib/rubocop/cop/utils/format_string.rb', line 94

def initialize(string)
  @source = string
end

Instance Method Details

#format_sequencesObject



98
99
100
# File 'lib/rubocop/cop/utils/format_string.rb', line 98

def format_sequences
  @format_sequences ||= parse
end

#max_digit_dollar_numObject



110
111
112
# File 'lib/rubocop/cop/utils/format_string.rb', line 110

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

#named_interpolation?Boolean

Returns:

  • (Boolean)


106
107
108
# File 'lib/rubocop/cop/utils/format_string.rb', line 106

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

#valid?Boolean

Returns:

  • (Boolean)


102
103
104
# File 'lib/rubocop/cop/utils/format_string.rb', line 102

def valid?
  !mixed_formats?
end
OSZAR »