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.'

Constants inherited from Cop

Cop::OPERATOR_METHODS

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offences, #processed_source

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?, #autocorrect_action, #convention, #cop_config, #cop_name, cop_name, cop_type, #debug?, #ignore_node, inherited, #initialize, lint?, #message, rails?, style?, #warning

Constructor Details

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

Instance Method Details

#check(t1, t2) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/rubocop/cop/style/surrounding_space.rb', line 305

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 cop_config['EnforcedStyleIsWithSpaces']
                       [!has_space, 'missing']
                     else
                       [has_space, 'detected']
                     end
  brace_token = t1.text == '{' ? t1 : t2
  convention(nil, brace_token.pos, sprintf(MSG, word)) if is_offence
end

#investigate(processed_source) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/rubocop/cop/style/surrounding_space.rb', line 290

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

  on_node(:hash, processed_source.ast) do |hash|
    b_ix = index_of_first_token(hash)
    e_ix = index_of_last_token(hash)
    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