Sha256: e393f29d120d3fc5b1d39d20fb22483ff6b77908d6a559576dfd8e412c87bb78

Contents?: true

Size: 1.28 KB

Versions: 26

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for options hashes and discourages them if the
      # current Ruby version supports keyword arguments.
      #
      # @example
      #
      #   # bad
      #   def fry(options = {})
      #     temperature = options.fetch(:temperature, 300)
      #     # ...
      #   end
      #
      #
      #   # good
      #   def fry(temperature: 300)
      #     # ...
      #   end
      class OptionHash < Cop
        MSG = 'Prefer keyword arguments to options hashes.'

        def_node_matcher :option_hash, <<~PATTERN
          (args ... $(optarg [#suspicious_name? _] (hash)))
        PATTERN

        def on_args(node)
          return if super_used?(node)
          return if allowlist.include?(node.parent.method_name.to_s)

          option_hash(node) do |options|
            add_offense(options)
          end
        end

        private

        def allowlist
          cop_config['Allowlist'] || []
        end

        def suspicious_name?(arg_name)
          cop_config.key?('SuspiciousParamNames') &&
            cop_config['SuspiciousParamNames'].include?(arg_name.to_s)
        end

        def super_used?(node)
          node.parent.each_node(:zsuper).any?
        end
      end
    end
  end
end

Version data entries

26 entries across 25 versions & 5 rubygems

Version Path
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.79.0/lib/rubocop/cop/style/option_hash.rb
rubocop-0.89.1 lib/rubocop/cop/style/option_hash.rb
rubocop-0.89.0 lib/rubocop/cop/style/option_hash.rb
rubocop-0.88.0 lib/rubocop/cop/style/option_hash.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/style/option_hash.rb
rubocop-0.87.1 lib/rubocop/cop/style/option_hash.rb
rubocop-0.87.0 lib/rubocop/cop/style/option_hash.rb
rubocop-0.86.0 lib/rubocop/cop/style/option_hash.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/style/option_hash.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/style/option_hash.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/style/option_hash.rb
rubocop-0.85.1 lib/rubocop/cop/style/option_hash.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/style/option_hash.rb
rubocop-0.85.0 lib/rubocop/cop/style/option_hash.rb
rubocop-0.84.0 lib/rubocop/cop/style/option_hash.rb
rubocop-0.83.0 lib/rubocop/cop/style/option_hash.rb
rubocop-0.82.0 lib/rubocop/cop/style/option_hash.rb
rubocop-0.81.0 lib/rubocop/cop/style/option_hash.rb
rubocop-0.80.1 lib/rubocop/cop/style/option_hash.rb
rubocop-0.80.0 lib/rubocop/cop/style/option_hash.rb