Class: RuboCop::Cop::GraphQL::OrderedArguments

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

Overview

Arguments should be alphabetically sorted within groups.

Examples:

# good

class UpdateProfile < BaseMutation
  argument :email, String, required: false
  argument :name, String, required: false
end

# good

class UpdateProfile < BaseMutation
  argument :uuid, ID, required: true

  argument :email, String, required: false
  argument :name, String, required: false
end

# good

class UserType < BaseType
  field :posts, PostType do
    argument :created_after, ISO8601DateTime, required: false
    argument :created_before, ISO8601DateTime, required: false
  end
end

# bad

class UpdateProfile < BaseMutation
  argument :uuid, ID, required: true
  argument :name, String, required: false
  argument :email, String, required: false
end

# bad

class UserType < BaseType
  field :posts, PostType do
    argument :created_before, ISO8601DateTime, required: false
    argument :created_after, ISO8601DateTime, required: false
  end
end

Constant Summary collapse

MSG =
"Arguments 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

#on_class(node) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rubocop/cop/graphql/ordered_arguments.rb', line 60

def on_class(node)
  declarations_with_blocks = argument_declarations_with_blocks(node)
  declarations_without_blocks = argument_declarations_without_blocks(node)

  argument_declarations = declarations_without_blocks.map do |node|
    arg_name = argument_name(node)
    same_arg_with_block_declaration = declarations_with_blocks.find do |dec|
      argument_name(dec) == arg_name
    end

    same_arg_with_block_declaration || node
  end

  argument_declarations.each_cons(2) do |previous, current|
    next unless consecutive_lines(previous, current)
    next if correct_order?(argument_name(previous), argument_name(current))

    register_offense(previous, current)
  end
end