Class: RuboCop::Cop::GraphQL::FieldTypeInBlock

Inherits:
BaseCop
  • Object
show all
Defined in:
lib/rubocop/cop/graphql/field_type_in_block.rb

Overview

Identify (and auto-correct) any field whose type configuration isn't given in the configuration block.

Examples:

# bad, immediately causes Rails to load `app/graphql/types/thing.rb`
field :thing, Types::Thing
field :thing, Types::Thing { description "A thing" }

# good, defers loading until the file is needed
field :thing do
  type(Types::Thing)
end
field :thing { type(Types::Thing) }

Constant Summary collapse

MSG =

rubocop:disable Metrics/ClassLength

"type configuration can be moved to a block to defer loading the type's file"
BUILT_IN_SCALAR_NAMES =
%w[Float Int Integer String ID Boolean].freeze

Instance Method Summary collapse

Methods inherited from BaseCop

#source_without_keyword_argument

Instance Method Details

#on_block(node) ⇒ Object

rubocop:disable Metrics/MethodLength



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/graphql/field_type_in_block.rb', line 40

def on_block(node) # rubocop:disable Metrics/MethodLength
  ignore_node(node)
  field_config_with_inline_type_and_block(node) do |type_const|
    type_const_str = get_type_argument_str(node, type_const)
    if ignore_inline_type_str?(type_const_str)
      # Do nothing ...
    else
      add_offense(type_const) do |corrector|
        cleaned_node_source = delete_type_argument(node, type_const)
        field_indent = determine_field_indent(node)
        cleaned_node_source.sub!(/(\{|do)/, "\\1\n#{field_indent}  type #{type_const_str}")
        corrector.replace(node, cleaned_node_source)
      end
    end
  end
end

#on_send(node) ⇒ Object

rubocop:disable Metrics/MethodLength



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rubocop/cop/graphql/field_type_in_block.rb', line 57

def on_send(node) # rubocop:disable Metrics/MethodLength
  return if part_of_ignored_node?(node)

  field_config_with_inline_type(node) do |type_const|
    type_const_str = get_type_argument_str(node, type_const)
    if ignore_inline_type_str?(type_const_str)
      # Do nothing -- not loading from another file
    else
      add_offense(type_const) do |corrector|
        cleaned_node_source = delete_type_argument(node, type_const)
        field_indent = determine_field_indent(node)
        cleaned_node_source += " do\n#{field_indent}  type #{type_const_str}\n#{field_indent}end"
        corrector.replace(node, cleaned_node_source)
      end
    end
  end
end