Class: RuboCop::Cop::GraphQL::OrderedFields

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
GraphQL::CompareOrder, GraphQL::SwapRange
Defined in:
lib/rubocop/cop/graphql/ordered_fields.rb

Overview

Fields should be alphabetically sorted within groups.

Examples:

# good

class UserType < BaseType
  field :name, String, null: true
  field :phone, String, null: true do
    argument :something, String, required: false
  end
end

# good

class UserType < BaseType
  field :phone, String, null: true

  field :name, String, null: true
end

# bad

class UserType < BaseType
  field :phone, String, null: true
  field :name, String, null: true
end

Constant Summary collapse

MSG =
"Fields should be sorted in an alphabetical order within their "\
"section. "\
"Field `%<current>s` should appear before `%<previous>s`."

Instance Method Summary collapse

Methods included from GraphQL::CompareOrder

#correct_order?, #order_index

Methods included from GraphQL::SwapRange

#declaration, #final_end_location, #swap_range

Instance Method Details

#field_declarations(node) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/rubocop/cop/graphql/ordered_fields.rb', line 44

def_node_search :field_declarations, <<~PATTERN
  {
    (send nil? :field (:sym _) ...)
    (block
      (send nil? :field (:sym _) ...) ...)
  }
PATTERN

#on_block(node) ⇒ Object Also known as: on_itblock, on_numblock



58
59
60
61
62
63
64
# File 'lib/rubocop/cop/graphql/ordered_fields.rb', line 58

def on_block(node)
  return if node.method?(:field)
  return unless node.each_ancestor(:class, :module).any?

  fields = field_declarations(node).select { |f| f.each_ancestor(:block).first == node }
  check_field_ordering(fields)
end

#on_class(node) ⇒ Object Also known as: on_module



52
53
54
# File 'lib/rubocop/cop/graphql/ordered_fields.rb', line 52

def on_class(node)
  check_field_ordering(direct_field_declarations(node))
end