class RuboCop::Cop::Style::KeywordArgumentsMerging

When passing an existing hash as keyword arguments, provide additional arguments directly rather than using ‘merge`.

Providing arguments directly is more performant, than using ‘merge`, and also leads to a shorter and simpler code.

@example

# bad
some_method(**opts.merge(foo: true))
some_method(**opts.merge(other_opts))

# good
some_method(**opts, foo: true)
some_method(**opts, **other_opts)

Constants

MSG

Public Instance Methods

on_kwsplat(node) click to toggle source
# File lib/rubocop/cop/style/keyword_arguments_merging.rb, line 36
def on_kwsplat(node)
  return unless (ancestor = node.parent&.parent)

  merge_kwargs?(ancestor) do |merge_node, hash_node, other_hash_node|
    add_offense(merge_node) do |corrector|
      autocorrect(corrector, node, hash_node, other_hash_node)
    end
  end
end

Private Instance Methods

autocorrect(corrector, kwsplat_node, hash_node, other_hash_node) click to toggle source
# File lib/rubocop/cop/style/keyword_arguments_merging.rb, line 48
def autocorrect(corrector, kwsplat_node, hash_node, other_hash_node)
  other_hash_node_replacement =
    other_hash_node.map do |node|
      if node.hash_type?
        if node.braces?
          node.source[1...-1]
        else
          node.source
        end
      else
        "**#{node.source}"
      end
    end.join(', ')

  corrector.replace(kwsplat_node, "**#{hash_node.source}, #{other_hash_node_replacement}")
end