no_to_sym_on_string.rb 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module RuboCop
  3. module Cop
  4. module Zammad
  5. # This cop is used to identify usages of `.to_sym` on Strings and
  6. # changes them to use the `:` prefix instead.
  7. #
  8. # @example
  9. # # bad
  10. # "a-Symbol".to_sym
  11. # 'a-Symbol'.to_sym
  12. # "a-#{'Symbol'}".to_sym
  13. #
  14. # # good
  15. # :"a-Symbol"
  16. # :'a-Symbol'
  17. # :"a-#{'Symbol'}"
  18. class NoToSymOnString < Base
  19. extend AutoCorrector
  20. def_node_matcher :to_sym?, <<-PATTERN
  21. {
  22. $(send (str ...) :to_sym ...)
  23. $(send (dstr ...) :to_sym ...)
  24. }
  25. PATTERN
  26. MSG = "Don't use `.to_sym` on String. Prefer `:` prefix instead.".freeze
  27. def on_send(node)
  28. result = *to_sym?(node)
  29. return if result.empty?
  30. add_offense(node, message: MSG) do |corrector|
  31. corrector.replace(node, ":#{result.first.source}")
  32. end
  33. end
  34. end
  35. end
  36. end
  37. end