Sha256: 47541785c828822d21b37bbac2c925fde763fb5384b48a1fca844d90382f9425

Contents?: true

Size: 1.67 KB

Versions: 11

Compression:

Stored size: 1.67 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Rails
      # This cop looks for delegations that pass :allow_blank as an option
      # instead of :allow_nil. :allow_blank is not a valid option to pass
      # to ActiveSupport#delegate.
      #
      # @example
      #   # bad
      #   delegate :foo, to: :bar, allow_blank: true
      #
      #   # good
      #   delegate :foo, to: :bar, allow_nil: true
      class DelegateAllowBlank < Cop
        MSG = '`allow_blank` is not a valid option, use `allow_nil`.'.freeze

        def_node_matcher :delegate, <<-PATTERN
          (send _ :delegate _ $hash)
        PATTERN

        def_node_matcher :delegate_options, <<-PATTERN
          (hash $...)
        PATTERN

        def_node_matcher :allow_blank?, <<-PATTERN
          (pair $(sym :allow_blank) true)
        PATTERN

        def on_send(node)
          offending_node = allow_blank_option(node)
          return unless offending_node

          allow_blank = offending_node.children.first
          add_offense(node, allow_blank.source_range, MSG)
        end

        def autocorrect(node)
          offending_node = allow_blank_option(node)
          return unless offending_node

          allow_blank = offending_node.children.first
          lambda do |corrector|
            corrector.replace(allow_blank.source_range, 'allow_nil')
          end
        end

        private

        def allow_blank_option(node)
          options_hash = delegate(node)
          return unless options_hash
          options = delegate_options(options_hash)
          return unless options

          options.detect { |opt| allow_blank?(opt) }
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/delegate_allow_blank.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/delegate_allow_blank.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/delegate_allow_blank.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/delegate_allow_blank.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/delegate_allow_blank.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/delegate_allow_blank.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/rails/delegate_allow_blank.rb
rubocop-0.46.0 lib/rubocop/cop/rails/delegate_allow_blank.rb
rubocop-0.45.0 lib/rubocop/cop/rails/delegate_allow_blank.rb
rubocop-0.44.1 lib/rubocop/cop/rails/delegate_allow_blank.rb
rubocop-0.44.0 lib/rubocop/cop/rails/delegate_allow_blank.rb