class RuboCop::Cop::Layout::SpaceInsideParens
y()
g = ( a + 3 )
f( 3 )
# good
y( )
g = (a + 3)
f(3)
# bad
# Note: Empty parentheses should not have spaces.
# beginning and end.
# The ‘space` style enforces that parentheses have a space at the
@example EnforcedStyle: space
g = (a + 3)
f(3)
# good
g = (a + 3 )
f( 3)
# bad
# The `no_space` style enforces that parentheses do not have spaces.
@example EnforcedStyle: no_space (default)
Checks for spaces inside ordinary round parentheses.
def autocorrect(range)
def autocorrect(range) lambda do |corrector| if style == :space corrector.insert_before(range, ' ') else corrector.remove(range) end end end
def can_be_ignored?(token1, token2)
def can_be_ignored?(token1, token2) return true unless parens?(token1, token2) # If the second token is a comment, that means that a line break # follows, and that the rules for space inside don't apply. return true if token2.comment? return true unless same_line?(token1, token2) && !token1.space_after? end
def each_extraneous_space(tokens)
def each_extraneous_space(tokens) tokens.each_cons(2) do |token1, token2| next unless parens?(token1, token2) # If the second token is a comment, that means that a line break # follows, and that the rules for space inside don't apply. next if token2.comment? next unless same_line?(token1, token2) && token1.space_after? yield range_between(token1.end_pos, token2.begin_pos) end end
def each_missing_space(tokens)
def each_missing_space(tokens) tokens.each_cons(2) do |token1, token2| next if can_be_ignored?(token1, token2) if token1.left_parens? yield range_between(token2.begin_pos, token2.begin_pos + 1) elsif token2.right_parens? yield range_between(token2.begin_pos, token2.end_pos) end end end
def investigate(processed_source)
def investigate(processed_source) @processed_source = processed_source if style == :space each_missing_space(processed_source.tokens) do |range| add_offense(range, location: range, message: MSG_SPACE) end else each_extraneous_space(processed_source.tokens) do |range| add_offense(range, location: range) end end end
def parens?(token1, token2)
def parens?(token1, token2) token1.left_parens? || token2.right_parens? end
def same_line?(token1, token2)
def same_line?(token1, token2) token1.line == token2.line end