Sha256: ed9780cf9bef8818e27827086f40884f5cc9d855da8fd3d2ab7b393f5554cdb6

Contents?: true

Size: 1.63 KB

Versions: 13

Compression:

Stored size: 1.63 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Enforces the use of consistent method names
      # `Object#yield_self` or `Object#then`.
      #
      # @example EnforcedStyle: then (default)
      #
      #   # bad
      #   obj.yield_self { |x| x.do_something }
      #
      #   # good
      #   obj.then { |x| x.do_something }
      #
      # @example EnforcedStyle: yield_self
      #
      #   # bad
      #   obj.then { |x| x.do_something }
      #
      #   # good
      #   obj.yield_self { |x| x.do_something }
      #
      class ObjectThen < Base
        include ConfigurableEnforcedStyle
        extend AutoCorrector

        MSG = 'Prefer `%<prefer>s` over `%<current>s`.'

        def on_block(node)
          check_method_node(node.send_node)
        end

        alias on_numblock on_block

        def on_send(node)
          return unless node.arguments.one? && node.first_argument.block_pass_type?

          check_method_node(node)
        end

        private

        def check_method_node(node)
          return unless preferred_method(node)

          message = message(node)
          add_offense(node.loc.selector, message: message) do |corrector|
            corrector.replace(node.loc.selector, style.to_s)
          end
        end

        def preferred_method(node)
          case style
          when :then
            node.method?(:yield_self)
          when :yield_self
            node.method?(:then)
          else
            false
          end
        end

        def message(node)
          format(MSG, prefer: style.to_s, current: node.method_name)
        end
      end
    end
  end
end

Version data entries

13 entries across 11 versions & 3 rubygems

Version Path
cm-admin-1.5.22 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/object_then.rb
cm-admin-1.5.21 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/object_then.rb
cm-admin-1.5.20 vendor/bundle/ruby/3.3.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/object_then.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/object_then.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.36.0/lib/rubocop/cop/style/object_then.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.35.1/lib/rubocop/cop/style/object_then.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.36.0/lib/rubocop/cop/style/object_then.rb
rubocop-1.38.0 lib/rubocop/cop/style/object_then.rb
rubocop-1.37.1 lib/rubocop/cop/style/object_then.rb
rubocop-1.37.0 lib/rubocop/cop/style/object_then.rb
rubocop-1.36.0 lib/rubocop/cop/style/object_then.rb
rubocop-1.35.1 lib/rubocop/cop/style/object_then.rb
rubocop-1.35.0 lib/rubocop/cop/style/object_then.rb