class Ducalis::FetchExpression

Constants

HASH_CALLING_REGEX
OFFENSE

Public Instance Methods

investigate(processed_source) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 20
def investigate(processed_source)
  return unless processed_source.ast

  matching_nodes(processed_source.ast).each do |node|
    add_offense(node, :expression, format(OFFENSE,
                                          source: correct_variant(node)))
  end
end

Private Instance Methods

construct_fetch(hash, key, default) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 75
def construct_fetch(hash, key, default)
  [source(hash), ".fetch(#{source(key)})", " { #{source(default)} }"].join
end
correct_variant(node) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 57
def correct_variant(node)
  if nil_matching?(node)
    nil_correct(node)
  else
    present_correct(node)
  end
end
matching_nodes(ast) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 31
def matching_nodes(ast)
  [
    *ternar_gets_present(ast).select(&method(:matching_ternar?)),
    *ternar_gets_nil(ast).select(&method(:matching_ternar?)),
    *default_gets(ast)
  ].uniq
end
matching_ternar?(node) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 43
def matching_ternar?(node)
  present_matching?(node) || nil_matching?(node)
end
nil_correct(node) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 65
def nil_correct(node)
  hash, _, key = *node.to_a.last.to_a
  construct_fetch(hash, key, node.to_a[1])
end
nil_matching?(node) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 52
def nil_matching?(node)
  source, _, result = *node
  (source.to_a.first == result && result.to_s =~ HASH_CALLING_REGEX)
end
present_correct(node) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 70
def present_correct(node)
  hash, _, key = *node.to_a.first.to_a
  construct_fetch(hash, key, node.to_a.last)
end
present_matching?(node) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 47
def present_matching?(node)
  source, result, = *node
  (source == result && result.to_s =~ HASH_CALLING_REGEX)
end
source(node) click to toggle source
# File lib/ducalis/cops/fetch_expression.rb, line 79
def source(node)
  node.loc.expression.source
end