Class: Rubocop::Cop::Style::SpaceInsideHashLiteralBraces

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

Overview

Checks that braces used for hash literals have or don't have surrounding space depending on configuration.

Constant Summary collapse

MSG =
'Space inside hash literal braces %s.'

Instance Attribute Summary

Attributes inherited from Cop

#autocorrect, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods included from SurroundingSpace

#build_token_table, #index_of_first_token, #index_of_last_token, #space_between?

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) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/rubocop/cop/style/surrounding_space.rb', line 278

def check(t1, t2)
  types = [t1, t2].map(&:type)
  braces = [:tLBRACE, :tRCURLY]
  return if types == braces || (braces - types).size == 2
  # No offence if line break inside.
  return if t1.pos.line < t2.pos.line
  has_space = space_between?(t1, t2)
  is_offence, word = if self.class.config['EnforcedStyleIsWithSpaces']
                       [!has_space, 'missing']
                     else
                       [has_space, 'detected']
                     end
  add_offence(:convention, t1.pos, sprintf(MSG, word)) if is_offence
end

#inspect(source_buffer, source, tokens, sexp, comments) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/rubocop/cop/style/surrounding_space.rb', line 265

def inspect(source_buffer, source, tokens, sexp, comments)
  return unless sexp
  @source = source
  on_node(:hash, sexp) do |hash|
    b_ix = index_of_first_token(hash, tokens)
    e_ix = index_of_last_token(hash, tokens)
    if tokens[b_ix].type == :tLBRACE # Hash literal with braces?
      check(tokens[b_ix], tokens[b_ix + 1])
      check(tokens[e_ix - 1], tokens[e_ix])
    end
  end
end