Class: RuboCop::Cop::Legion::HelperMigration::DirectLocalCache

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/legion/helper_migration/direct_local_cache.rb

Overview

Detects direct calls to ‘Legion::Cache::Local` methods and suggests using the `local_cache_*` helpers instead.

Examples:

# bad
Legion::Cache::Local.get('key')
Legion::Cache::Local.set('key', value)
Legion::Cache::Local.delete('key')
Legion::Cache::Local.fetch('key') { compute }

# good
local_cache_get('key')
local_cache_set('key', value)
local_cache_delete('key')
local_cache_fetch('key') { compute }

Constant Summary collapse

MSG =
'Use `%<helper>s` instead of `Legion::Cache::Local.%<method>s`. ' \
'Include the appropriate local cache helper mixin.'
RESTRICT_ON_SEND =
%i[get set delete fetch].freeze
HELPER_MAP =
{
  get: 'local_cache_get',
  set: 'local_cache_set',
  delete: 'local_cache_delete',
  fetch: 'local_cache_fetch'
}.freeze

Instance Method Summary collapse

Instance Method Details

#legion_local_cache_call?(node) ⇒ Object



38
39
40
# File 'lib/rubocop/cop/legion/helper_migration/direct_local_cache.rb', line 38

def_node_matcher :legion_local_cache_call?, <<~PATTERN
  (send (const (const (const nil? :Legion) :Cache) :Local) {:get :set :delete :fetch} ...)
PATTERN

#on_send(node) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rubocop/cop/legion/helper_migration/direct_local_cache.rb', line 42

def on_send(node)
  return unless legion_local_cache_call?(node)

  method_name = node.method_name
  helper = HELPER_MAP[method_name]
  message = format(MSG, helper: helper, method: method_name)

  add_offense(node, message: message) do |corrector|
    args_source = node.arguments.map(&:source).join(', ')
    corrector.replace(node, "#{helper}(#{args_source})")
  end
end