Module: RuboCop::Cop::SpaceBeforePunctuation

Included in:
Layout::SpaceBeforeComma, Layout::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 %<token>s.'.freeze

Instance Method Summary collapse

Instance Method Details

#autocorrect(pos_before_punctuation) ⇒ Object



17
18
19
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 17

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

#each_missing_space(tokens) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 21

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)

    pos_before_punctuation = range_between(t1.end_pos,
                                           t2.begin_pos)

    yield t2, pos_before_punctuation
  end
end

#investigate(processed_source) ⇒ Object



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

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

#space_missing?(t1, t2) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 34

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

#space_required_after?(token) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/rubocop/cop/mixin/space_before_punctuation.rb', line 38

def space_required_after?(token)
  token.left_curly_brace? && space_required_after_lcurly?
end

#space_required_after_lcurly?Boolean

Returns:

  • (Boolean)


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

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