Module: RuboCop::Cop::SpaceBeforePunctuation

Included in:
RuboCop::Cop::Style::SpaceBeforeComma, RuboCop::Cop::Style::SpaceBeforeSemicolon
Defined in:
lib/rubocop/cop/mixin/space_before_punctuation.rb

Overview

Common functionality for cops checking for space before punctuation.

Constant Summary collapse

MSG =
'Space found before %s.'.freeze

Instance Method Summary collapse

Instance Method Details

#autocorrect(pos_before_punctuation) ⇒ Object



46
47
48
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 46

def autocorrect(pos_before_punctuation)
  ->(corrector) { corrector.remove(pos_before_punctuation) }
end

#each_missing_space(tokens) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 17

def each_missing_space(tokens)
  tokens.each_cons(2) do |t1, t2|
    next unless kind(t2)
    next unless space_missing?(t1, t2)
    next if space_required_after?(t1)

    buffer = processed_source.buffer
    pos_before_punctuation = Parser::Source::Range.new(buffer,
                                                       t1.pos.end_pos,
                                                       t2.pos.begin_pos)

    yield t2, pos_before_punctuation
  end
end

#investigate(processed_source) ⇒ Object



11
12
13
14
15
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 11

def investigate(processed_source)
  each_missing_space(processed_source.tokens) do |token, pos_before|
    add_offense(pos_before, pos_before, format(MSG, kind(token)))
  end
end

#space_missing?(t1, t2) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 32

def space_missing?(t1, t2)
  t1.pos.line == t2.pos.line && t2.pos.begin_pos > t1.pos.end_pos
end

#space_required_after?(token) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 36

def space_required_after?(token)
  token.type == :tLCURLY && space_required_after_lcurly?
end

#space_required_after_lcurly?Boolean

Returns:

  • (Boolean)


40
41
42
43
44
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 40

def space_required_after_lcurly?
  cfg = config.for_cop('Style/SpaceInsideBlockBraces')
  style = cfg['EnforcedStyle'] || 'space'
  style == 'space'
end