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_class(node) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/rubocop/cop/graphql/ordered_fields.rb', line 52

def on_class(node)
  field_declarations(node).each_cons(2) do |previous, current|
    next unless consecutive_fields(previous, current)
    next if correct_order?(field_name(previous), field_name(current))

    register_offense(previous, current)
  end
end