Class: Rubocop::Cop::Style::SpaceAroundBraces

Inherits:
Cop
  • Object
show all
Includes:
SurroundingSpace
Defined in:
lib/rubocop/cop/style/surrounding_space.rb

Overview

Checks that block braces have surrounding space.

Constant Summary collapse

MSG_LEFT =
"Surrounding space missing for '{'."
MSG_RIGHT =
"Space missing to the left of '}'."

Instance Attribute Summary

Attributes inherited from Cop

#autocorrect, #corrections, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods included from SurroundingSpace

#index_of_first_token, #index_of_last_token, #space_between?, #token_table

Methods inherited from Cop

#add_offence, all, #autocorrect_action, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, lint?, #name, rails?, style?

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#check(t1, t2, msg) ⇒ Object



224
225
226
227
228
229
# File 'lib/rubocop/cop/style/surrounding_space.rb', line 224

def check(t1, t2, msg)
  unless space_between?(t1, t2)
    brace_token = msg == MSG_LEFT ? t1 : t2
    add_offence(:convention, brace_token.pos, msg)
  end
end

#investigate(processed_source) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/rubocop/cop/style/surrounding_space.rb', line 183

def investigate(processed_source)
  return unless processed_source.ast
  @processed_source = processed_source

  processed_source.tokens.each_cons(2) do |t1, t2|
    next if ([t1.pos, t2.pos] - positions_not_to_check).size < 2

    type1, type2 = t1.type, t2.type
    # :tLBRACE in hash literals, :tLCURLY otherwise.
    next if [:tLCURLY, :tLBRACE].include?(type1) && type2 == :tRCURLY
    check(t1, t2, MSG_LEFT) if type1 == :tLCURLY || type2 == :tLCURLY
    check(t1, t2, MSG_RIGHT) if type2 == :tRCURLY
  end
end

#positions_not_to_checkObject



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/rubocop/cop/style/surrounding_space.rb', line 198

def positions_not_to_check
  @positions_not_to_check ||= begin
    positions = []
    ast = @processed_source.ast
    tokens = @processed_source.tokens

    on_node(:hash, ast) do |hash|
      b_ix = index_of_first_token(hash)
      e_ix = index_of_last_token(hash)
      positions << tokens[b_ix].pos << tokens[e_ix].pos
    end

    # TODO: Check braces inside string/symbol/regexp/xstr
    #   interpolation.
    on_node([:dstr, :dsym, :regexp, :xstr], ast) do |s|
      b_ix = index_of_first_token(s)
      e_ix = index_of_last_token(s)
      tokens[b_ix..e_ix].each do |t|
        positions << t.pos if t.type == :tRCURLY
      end
    end

    positions
  end
end