class RuboCop::Cop::Style::EmptyLiteral
This cop checks for the use of a method, the result of which would be a literal, like an empty array, hash or string.
Constants
- ARRAY_NODE
Empty array node
(send
(const nil :Array) :new)
- ARR_MSG
- HASH_MSG
- HASH_NODE
Empty hash node
(send
(const nil :Hash) :new)
- STR_MSG
- STR_NODE
Empty string node
(send
(const nil :String) :new)
Public Instance Methods
autocorrect(node)
click to toggle source
# File lib/rubocop/cop/style/empty_literal.rb, line 45 def autocorrect(node) name = case node when ARRAY_NODE '[]' when HASH_NODE # `some_method {}` is not same as `some_method Hash.new` # because the braces are interpreted as a block, so we avoid # the correction. Parentheses around the arguments would # solve the problem, but we let the user add those manually. return if first_arg_in_method_call_without_parentheses?(node) '{}' when STR_NODE if enforce_double_quotes? '""' else "''" end end ->(corrector) { corrector.replace(node.source_range, name) } end
on_send(node)
click to toggle source
# File lib/rubocop/cop/style/empty_literal.rb, line 31 def on_send(node) case node when ARRAY_NODE add_offense(node, :expression, ARR_MSG) when HASH_NODE # If Hash.new takes a block, it can't be changed to {}. return if node.parent && node.parent.block_type? add_offense(node, :expression, HASH_MSG) when STR_NODE add_offense(node, :expression, STR_MSG) end end
Private Instance Methods
enforce_double_quotes?()
click to toggle source
# File lib/rubocop/cop/style/empty_literal.rb, line 68 def enforce_double_quotes? string_literals_config['EnforcedStyle'] == 'double_quotes' end
first_arg_in_method_call_without_parentheses?(node)
click to toggle source
# File lib/rubocop/cop/style/empty_literal.rb, line 76 def first_arg_in_method_call_without_parentheses?(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
string_literals_config()
click to toggle source
# File lib/rubocop/cop/style/empty_literal.rb, line 72 def string_literals_config config.for_cop('Style/StringLiterals') end