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 =
/(\d+)\$/.freeze
FLAG =
/[ #0+-]|#{DIGIT_DOLLAR}/.freeze
NUMBER_ARG =
/\*#{DIGIT_DOLLAR}?/.freeze
NUMBER =
/\d+|#{NUMBER_ARG}/.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.



89
90
91
# File 'lib/rubocop/cop/utils/format_string.rb', line 89

def initialize(string)
  @source = string
end

Instance Method Details

#format_sequencesObject



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

def format_sequences
  @format_sequences ||= parse
end

#max_digit_dollar_numObject



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

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

#named_interpolation?Boolean

Returns:

  • (Boolean)


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

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

#valid?Boolean

Returns:

  • (Boolean)


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

def valid?
  !mixed_formats?
end