Class: GraphQL::Schema::Object

Inherits:
BasicObject
Includes:
Member::GraphQLTypeNames
Defined in:
lib/grate/graphql_object.rb

Class Method Summary collapse

Class Method Details

.camelize(name) ⇒ Object



5
6
7
# File 'lib/grate/graphql_object.rb', line 5

def self.camelize(name)
  name.split('_').collect(&:capitalize).join
end

.get_controller(model_name) ⇒ Object



12
13
14
15
# File 'lib/grate/graphql_object.rb', line 12

def self.get_controller(model_name)
  controller_name = "#{model_name.pluralize}Controller"
  Object.const_get(controller_name)
end

.is_valid_type_nameObject



8
9
10
# File 'lib/grate/graphql_object.rb', line 8

def self.is_valid_type_name
  self.to_s.chars.last(4).join == 'Type'
end

.queryable_on(field_name, field_type) ⇒ Object

Raises:

  • (NameError)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/grate/graphql_object.rb', line 17

def self.queryable_on(field_name, field_type)
  raise NameError,
        "#{self} is invalid type name. Types must end in -Type" unless is_valid_type_name

  # Gets all the various model, type and controller names.
  model = self.to_s.chomp('Type')
  type_name = self
  model_name = model.downcase
  controller = get_controller(model)
  
  if field_name == :id
    query_name = function_name = model_name
    return_type = type_name
  else
    query_name = "#{model_name}By#{camelize(field_name.to_s)}"
    function_name = "#{model_name}_by_#{field_name}"
    return_type = [type_name]
  end
  
  QueryType.class_eval do
    field query_name,
          return_type,
          null: true do
      description "Query #{model} by #{field_name}"
      argument field_name, field_type, required: true
    end
    define_method function_name do |query_args|
      controller.find_by(query_args[field_name], field_name)
    end
  end
end