File: variable_definition.rb

package info (click to toggle)
ruby-rubocop-rspec 2.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,892 kB
  • sloc: ruby: 22,283; makefile: 4
file content (74 lines) | stat: -rw-r--r-- 1,822 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      # Checks that memoized helpers names are symbols or strings.
      #
      # @example EnforcedStyle: symbols (default)
      #   # bad
      #   subject('user') { create_user }
      #   let('user_name') { 'Adam' }
      #
      #   # good
      #   subject(:user) { create_user }
      #   let(:user_name) { 'Adam' }
      #
      # @example EnforcedStyle: strings
      #   # bad
      #   subject(:user) { create_user }
      #   let(:user_name) { 'Adam' }
      #
      #   # good
      #   subject('user') { create_user }
      #   let('user_name') { 'Adam' }
      #
      class VariableDefinition < Base
        extend AutoCorrector
        include ConfigurableEnforcedStyle
        include Variable

        MSG = 'Use %<style>s for variable names.'

        def on_send(node)
          variable_definition?(node) do |variable|
            next unless style_violation?(variable)

            add_offense(
              variable,
              message: format(MSG, style: style)
            ) do |corrector|
              corrector.replace(variable, correct_variable(variable))
            end
          end
        end

        private

        def correct_variable(variable)
          case variable.type
          when :dsym
            variable.source[1..]
          when :sym
            variable.value.to_s.inspect
          else
            variable.value.to_sym.inspect
          end
        end

        def style_violation?(variable)
          style == :symbols && string?(variable) ||
            style == :strings && symbol?(variable)
        end

        def string?(node)
          node.str_type?
        end

        def symbol?(node)
          node.sym_type? || node.dsym_type?
        end
      end
    end
  end
end