Class: RuboCop::Cop::GraphQL::FieldMethod

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp, GraphQL::NodePattern
Defined in:
lib/rubocop/cop/graphql/field_method.rb

Overview

This cop prevents defining unnecessary resolver methods in cases

when :method option can be used

Examples:

# good

class Types::UserType < Types::BaseObject
  field :phone, String, null: true, method: :home_phone
end

# bad

class Types::UserType < Types::BaseObject
  field :phone, String, null: true

  def phone
    object.home_phone
  end
end

Constant Summary collapse

MSG =
"Use method: :%<method_name>s"
RESTRICT_ON_SEND =
%i[field].freeze

Instance Method Summary collapse

Methods included from GraphQL::NodePattern

#argument?, #field?, #field_definition?, #field_definition_with_body?

Instance Method Details

#method_to_use(node) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/rubocop/cop/graphql/field_method.rb', line 32

def_node_matcher :method_to_use, <<~PATTERN
  (def
    _
    (args)
    (send
      (send nil? :object) $_
    )
  )
PATTERN

#on_send(node) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rubocop/cop/graphql/field_method.rb', line 45

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

  field = RuboCop::GraphQL::Field.new(node)
  method_definition = suggest_method_name_for(field)

  suggested_method_name = method_to_use(method_definition)

  return if suggested_method_name.nil?
  return if RuboCop::GraphQL::Field::CONFLICT_FIELD_NAMES.include?(suggested_method_name)
  return if method_kwarg_set?(field)

  add_offense(node, message: message(suggested_method_name)) do |corrector|
    autocorrect(corrector, node)
  end
end