123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Layout::SpaceInsideHashLiteralBraces

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb

Overview

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

Examples:

EnforcedStyle: space (default)

# The `space` style enforces that hash literals have
# surrounding space.

# bad
h = {a: 1, b: 2}

# good
h = { a: 1, b: 2 }

EnforcedStyle: no_space

# The `no_space` style enforces that hash literals have
# no surrounding space.

# bad
h = { a: 1, b: 2 }

# good
h = {a: 1, b: 2}

EnforcedStyle: compact

# The `compact` style normally requires a space inside
# hash braces, with the exception that successive left
# braces or right braces are collapsed together in nested hashes.

# bad
h = { a: { b: 2 } }
foo = { { a: 1 } => { b: { c: 2 } } }

# good
h = { a: { b: 2 }}
foo = {{ a: 1 } => { b: { c: 2 }}}

EnforcedStyleForEmptyBraces: no_space (default)

# The `no_space` EnforcedStyleForEmptyBraces style enforces that
# empty hash braces do not contain spaces.

# bad
foo = { }
bar = {    }
baz = {
}

# good
foo = {}
bar = {}
baz = {}

EnforcedStyleForEmptyBraces: space

# The `space` EnforcedStyleForEmptyBraces style enforces that
# empty hash braces contain space.

# bad
foo = {}

# good
foo = { }
foo = {    }
foo = {
}

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

::RuboCop::Cop::SurroundingSpace - Included

NO_SPACE_COMMAND, SINGLE_SPACE_REGEXP, SPACE_COMMAND

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

SYMBOL_TO_STRING_CACHE

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

.builtin?

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Cops (other than builtin) are encouraged to implement this.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

::RuboCop::Cop::SurroundingSpace - Included

::RuboCop::Cop::RangeHelp - Included

#add_range, #column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos, #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed,
#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?, #target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #range_for_original, #range_from_node_or_range, #reset_investigation, #use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Attribute Details

#enforce_no_space_style_for_empty_braces?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 202

def enforce_no_space_style_for_empty_braces?
  cop_config['EnforcedStyleForEmptyBraces'] == 'no_space'
end

Instance Method Details

#ambiguous_or_unexpected_style_detected(style, is_match) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 137

def ambiguous_or_unexpected_style_detected(style, is_match)
  if is_match
    ambiguous_style_detected(style, :compact)
  else
    unexpected_style_detected(style)
  end
end

#autocorrect(corrector, range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 129

def autocorrect(corrector, range)
  case range.source
  when /\s/ then corrector.remove(range)
  when '{' then corrector.insert_after(range, ' ')
  else corrector.insert_before(range, ' ')
  end
end

#check(token1, token2) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 89

def check(token1, token2)
  # No offense if line break inside.
  return if token1.line < token2.line
  return if token2.comment? # Also indicates there's a line break.

  is_empty_braces = token1.left_brace? && token2.right_curly_brace?
  expect_space    = expect_space?(token1, token2)

  if offense?(token1, expect_space)
    incorrect_style_detected(token1, token2, expect_space, is_empty_braces)
  else
    correct_style_detected
  end
end

#check_whitespace_only_hash(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 184

def check_whitespace_only_hash(node)
  range = range_inside_hash(node)
  return unless range.source.match?(/\A\s+\z/m)

  add_offense(
    range,
    message: format(MSG, problem: 'empty hash literal braces detected')
  ) do |corrector|
    corrector.remove(range)
  end
end

#expect_space?(token1, token2) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 104

def expect_space?(token1, token2)
  is_same_braces  = token1.type == token2.type
  is_empty_braces = token1.left_brace? && token2.right_curly_brace?

  if is_same_braces && style == :compact
    false
  elsif is_empty_braces
    !enforce_no_space_style_for_empty_braces?
  else
    style != :no_space
  end
end

#incorrect_style_detected(token1, token2, expect_space, is_empty_braces) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 117

def incorrect_style_detected(token1, token2,
                             expect_space, is_empty_braces)
  brace = (token1.left_brace? ? token1 : token2).pos
  range = expect_space ? brace : space_range(brace)
  detected_style = expect_space ? 'no_space' : 'space'

  add_offense(range, message: message(brace, is_empty_braces, expect_space)) do |corrector|
    autocorrect(corrector, range)
    ambiguous_or_unexpected_style_detected(detected_style, token1.text == token2.text)
  end
end

#message(brace, is_empty_braces, expect_space) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 150

def message(brace, is_empty_braces, expect_space)
  inside_what = if is_empty_braces
                  'empty hash literal braces'
                else
                  brace.source
                end
  problem = expect_space ? 'missing' : 'detected'
  format(MSG, problem: "#{inside_what} #{problem}")
end

#offense?(token1, expect_space) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 145

def offense?(token1, expect_space)
  has_space = token1.space_after?
  expect_space ? !has_space : has_space
end

#on_hash(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 78

def on_hash(node)
  tokens = processed_source.tokens_within(node)
  return unless tokens.first.left_brace? && tokens.last.right_curly_brace?

  check(tokens[0], tokens[1])
  check(tokens[-2], tokens[-1]) if tokens.size > 2
  check_whitespace_only_hash(node) if enforce_no_space_style_for_empty_braces?
end

#range_inside_hash(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 196

def range_inside_hash(node)
  return node.source_range if node.location.begin.nil?

  range_between(node.location.begin.end_pos, node.location.end.begin_pos)
end

#range_of_space_to_the_left(range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 176

def range_of_space_to_the_left(range)
  src = range.source_buffer.source
  begin_pos = range.begin_pos
  begin_pos -= 1 while /[ \t]/.match?(src[begin_pos - 1])

  range_between(begin_pos, range.end_pos - 1)
end

#range_of_space_to_the_right(range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 168

def range_of_space_to_the_right(range)
  src = range.source_buffer.source
  end_pos = range.end_pos
  end_pos += 1 while /[ \t]/.match?(src[end_pos])

  range_between(range.begin_pos + 1, end_pos)
end

#space_range(token_range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb', line 160

def space_range(token_range)
  if token_range.source == '{'
    range_of_space_to_the_right(token_range)
  else
    range_of_space_to_the_left(token_range)
  end
end