Class: GraphQL::Rubocop::GraphQL::FieldTypeInBlock

Inherits:
BaseCop
  • Object
show all
Defined in:
lib/graphql/rubocop/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

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

Constant Summary collapse

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

Instance Method Summary collapse

Methods inherited from BaseCop

#source_without_keyword_argument

Instance Method Details

#on_block(node) ⇒ Object



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

def on_block(node)
  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



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

def on_send(node)
  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