Sha256: c2d1b8e5807d257250165d9e9883eea707b05a9400f3629bdcc0fd270fd0512e

Contents?: true

Size: 1.42 KB

Versions: 156

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Checks for places where the `#\_\_dir\_\_` method can replace more
      # complex constructs to retrieve a canonicalized absolute path to the
      # current file.
      #
      # @example
      #   # bad
      #   path = File.expand_path(File.dirname(__FILE__))
      #
      #   # bad
      #   path = File.dirname(File.realpath(__FILE__))
      #
      #   # good
      #   path = __dir__
      class Dir < Base
        extend AutoCorrector
        extend TargetRubyVersion

        minimum_target_ruby_version 2.0

        MSG = "Use `__dir__` to get an absolute path to the current file's directory."
        RESTRICT_ON_SEND = %i[expand_path dirname].freeze

        # @!method dir_replacement?(node)
        def_node_matcher :dir_replacement?, <<~PATTERN
          {(send (const {nil? cbase} :File) :expand_path (send (const {nil? cbase} :File) :dirname  #file_keyword?))
           (send (const {nil? cbase} :File) :dirname     (send (const {nil? cbase} :File) :realpath #file_keyword?))}
        PATTERN

        def on_send(node)
          dir_replacement?(node) do
            add_offense(node) do |corrector|
              corrector.replace(node, '__dir__')
            end
          end
        end

        private

        def file_keyword?(node)
          node.str_type? && node.source_range.is?('__FILE__')
        end
      end
    end
  end
end

Version data entries

156 entries across 155 versions & 16 rubygems

Version Path
rubocop-1.74.0 lib/rubocop/cop/style/dir.rb
rubocop-1.73.2 lib/rubocop/cop/style/dir.rb
siteimprove_api_client-1.0.1 vendor/bundle/ruby/3.2.0/gems/rubocop-1.73.1/lib/rubocop/cop/style/dir.rb
rubocop-1.73.1 lib/rubocop/cop/style/dir.rb
rubocop-1.73.0 lib/rubocop/cop/style/dir.rb
rubocop-1.72.2 lib/rubocop/cop/style/dir.rb
rubocop-1.72.1 lib/rubocop/cop/style/dir.rb
rubocop-1.72.0 lib/rubocop/cop/style/dir.rb
rubocop-1.71.2 lib/rubocop/cop/style/dir.rb
tailscale_middleware-0.0.3 vendor/cache/ruby/3.4.0/gems/rubocop-1.71.1/lib/rubocop/cop/style/dir.rb
rubocop-1.71.1 lib/rubocop/cop/style/dir.rb
rubocop-1.71.0 lib/rubocop/cop/style/dir.rb
rubocop-1.70.0 lib/rubocop/cop/style/dir.rb
minato_ruby_api_client-0.2.2 vendor/bundle/ruby/3.2.0/gems/rubocop-1.64.1/lib/rubocop/cop/style/dir.rb
rubocop-1.69.2 lib/rubocop/cop/style/dir.rb
rubocop-1.69.1 lib/rubocop/cop/style/dir.rb
rubocop-1.69.0 lib/rubocop/cop/style/dir.rb
rubocop-1.68.0 lib/rubocop/cop/style/dir.rb
rubocop-1.67.0 lib/rubocop/cop/style/dir.rb
rubocop-1.66.1 lib/rubocop/cop/style/dir.rb