Class: GraphQL::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/node.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target = nil) ⇒ Node

Returns a new instance of Node.



4
5
6
7
# File 'lib/graphql/node.rb', line 4

def initialize(target=nil)
  # DONT EXPOSE Node#target! otherwise you might be able to access it
  @target = target
end

Instance Attribute Details

#fieldsObject

Returns the value of attribute fields.



2
3
4
# File 'lib/graphql/node.rb', line 2

def fields
  @fields
end

Class Method Details

.call(argument) ⇒ Object

Raises:

  • (NotImplementedError)


34
35
36
# File 'lib/graphql/node.rb', line 34

def self.call(argument)
  raise NotImplementedError, "Implement #{name}#call(argument) to use this node as a call"
end

.cursor(field_name) ⇒ Object



56
57
58
59
60
# File 'lib/graphql/node.rb', line 56

def self.cursor(field_name)
  define_method "cursor" do
    safe_send(field_name).to_s
  end
end

.edges(field_name, collection_class_name:, edge_class_name:) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/graphql/node.rb', line 46

def self.edges(field_name, collection_class_name:, edge_class_name:)
  define_method(field_name) do
    collection_items = @target.send(field_name)
    collection_class = Object.const_get(collection_class_name)
    edge_class = Object.const_get(edge_class_name)
    collection = collection_class.new(items: collection_items, edge_class: edge_class)
  end
end

.field_reader(*field_names) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/graphql/node.rb', line 38

def self.field_reader(*field_names)
  field_names.each do |field_name|
    define_method(field_name) do
      @target.public_send(field_name)
    end
  end
end

Instance Method Details

#safe_send(identifier) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/graphql/node.rb', line 9

def safe_send(identifier)
  if respond_to?(identifier)
    public_send(identifier)
  else
    raise GraphQL::FieldNotDefinedError, "#{self.class.name}##{identifier} was requested, but it isn't defined."
  end
end

#to_jsonObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/graphql/node.rb', line 17

def to_json
  json = {}
  fields.each do |field|
    name = field.identifier
    if field.is_a?(GraphQL::Syntax::Field)
      json[name] = safe_send(name)
    elsif field.is_a?(GraphQL::Syntax::Edge)
      edge = safe_send(field.identifier)
      edge.calls = field.call_hash
      edge.fields = field.fields
      json[name] = edge.to_json
    end
  end
  json
end