Class: RuboCop::Cop::GraphQL::UselessMethodOption

Inherits:
Base
  • Object
show all
Includes:
GraphQL::NodePattern
Defined in:
lib/rubocop/cop/graphql/useless_method_option.rb

Overview

This cop detects resolver_method: or method: options that have no effect, either because:

  • the same field also sets resolver: -- graphql-ruby always calls the resolver class's own resolver_method once resolver: is set, silently ignoring both resolver_method: and method: regardless of whether a method by either name exists; or
  • a method matching the field's own plain name is also defined on the type -- that method is checked (and wins) before method: is ever considered, since method: is only consulted as a fallback when no such method exists. This only applies to method:: resolver_method: redirects which name is checked instead of competing with it, so it can't be shadowed by a same-named def the way method: can.

Examples:

# good

class Types::PostType < Types::BaseObject
  field :author, resolver: Resolvers::AuthorResolver
end

class Types::PostType < Types::BaseObject
  field :author, String, null: true, method: :ghostwriter
end

# bad

class Types::PostType < Types::BaseObject
  field :author, resolver: Resolvers::AuthorResolver, resolver_method: :fetch_author
end

class Types::PostType < Types::BaseObject
  field :author, resolver: Resolvers::AuthorResolver, method: :ghostwriter
end

class Types::PostType < Types::BaseObject
  field :author, String, null: true, method: :ghostwriter

  def author
    object.author
  end
end

Constant Summary collapse

RESOLVER_MSG =
"Remove `%<option>s:`, it has no effect: `resolver: %<resolver>s` " \
"always takes precedence."
DEF_MSG =
"Remove `method:`, it has no effect: `def %<field_name>s` on the type " \
"always takes precedence."
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_pair(node) ⇒ Object



62
# File 'lib/rubocop/cop/graphql/useless_method_option.rb', line 62

def_node_search :method_pair, "(pair (sym :method) ...)"

#on_send(node) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/rubocop/cop/graphql/useless_method_option.rb', line 64

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

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

  if field.kwargs.resolver
    register_resolver_offenses(node, field)
  else
    register_method_shadowed_by_def_offense(node, field)
  end
end

#resolver_method_pair(node) ⇒ Object



59
# File 'lib/rubocop/cop/graphql/useless_method_option.rb', line 59

def_node_search :resolver_method_pair, "(pair (sym :resolver_method) ...)"