Sha256: 052d9117b3add0d432e544dea9d16ed29cf857e0a5c4d2a76eb81af69395c432

Contents?: true

Size: 1.22 KB

Versions: 71

Compression:

Stored size: 1.22 KB

Contents

# frozen_string_literal: true

module CustomCops
  class TimecopWithoutBlock < RuboCop::Cop::Cop
    MSG = 'Avoid using `Timecop.%<method>s` without providing a block.'

    def_node_matcher :timecop_method, '(send (const nil? :Timecop) ${:travel :freeze} ...)'

    def on_send(node)
      timecop_method(node) do |method_name|
        return if !method_name || first_child_of_block?(node) || last_child_is_a_block(node)

        add_offense(node, location: :selector, message: format(MSG, method: method_name))
      end
    end

    private

    # Checks if the given node's parent is a block, and the given node is its first child,
    # which would mean that the block is supplied to the given node (i.e `node { block }`)
    def first_child_of_block?(node)
      return false unless (parent = node.parent)

      return false unless parent.type == :block

      parent.children.first == node
    end

    # Checks whether the last child of the given node is a block.
    # this denotes the following structure:
    # `Timecop.method(arg1, arg2, &block)`, which is also a valid way of passing in a block
    def last_child_is_a_block(node)
      node.children.last&.type == :block_pass if node.children.last.respond_to?(:type)
    end
  end
end

Version data entries

71 entries across 71 versions & 1 rubygems

Version Path
simplycop-2.6.0 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.5.1 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.5.0 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.3.3 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.3.2 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.3.1 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.3.0 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.2.0 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.1.4 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.1.3 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.1.2 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.1.0 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.0.1 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-2.0.0 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-1.19.3 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-1.19.2 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-1.19.1 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-1.19.0 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-1.17.0 lib/simplycop/custom_cops/timecop_without_block.rb
simplycop-1.16.6 lib/simplycop/custom_cops/timecop_without_block.rb