class RuboCop::Cop::Style::EmptyLiteral
s = ”
h = {}
a = []
# good
s = String.new
h = Hash.new
a = Array.new
# bad
@example
would be a literal, like an empty array, hash or string.
This cop checks for the use of a method, the result of which
def autocorrect(node)
def autocorrect(node) lambda do |corrector| corrector.replace(replacement_range(node), correction(node)) end end
def correction(node)
def correction(node) if offense_array_node?(node) '[]' elsif str_node(node) preferred_string_literal elsif offense_hash_node?(node) if first_argument_unparenthesized?(node) # `some_method {}` is not same as `some_method Hash.new` # because the braces are interpreted as a block. We will have # to rewrite the arguments to wrap them in parenthesis. _receiver, _method_name, *args = *node.parent "(#{args[1..-1].map(&:source).unshift('{}').join(', ')})" else '{}' end end end
def enforce_double_quotes?
def enforce_double_quotes? string_literals_config['EnforcedStyle'] == 'double_quotes' end
def first_argument_unparenthesized?(node)
def first_argument_unparenthesized?(node) return false unless node.parent && node.parent.send_type? _receiver, _method_name, *args = *node.parent node.object_id == args.first.object_id && !parentheses?(node.parent) end
def offense_array_node?(node)
def offense_array_node?(node) array_node(node) && !array_with_block(node.parent) end
def offense_hash_node?(node)
def offense_hash_node?(node) # If Hash.new takes a block, it can't be changed to {}. hash_node(node) && !hash_with_block(node.parent) end
def on_send(node)
def on_send(node) add_offense(node, message: ARR_MSG) if offense_array_node?(node) add_offense(node, message: HASH_MSG) if offense_hash_node?(node) str_node(node) do return if frozen_string_literals_enabled? add_offense(node, message: format(STR_MSG, prefer: preferred_string_literal)) end end
def preferred_string_literal
def preferred_string_literal enforce_double_quotes? ? '""' : "''" end
def replacement_range(node)
def replacement_range(node) if hash_node(node) && first_argument_unparenthesized?(node) # `some_method {}` is not same as `some_method Hash.new` # because the braces are interpreted as a block. We will have # to rewrite the arguments to wrap them in parenthesis. _receiver, _method_name, *args = *node.parent range_between(args[0].loc.expression.begin_pos - 1, args[-1].loc.expression.end_pos) else node.source_range end end
def string_literals_config
def string_literals_config config.for_cop('Style/StringLiterals') end