Module: Rails::GraphQL::Helpers::WithAssignment

Included in:
Source::Base, Type::Input, Type::Interface, Type::Object
Defined in:
lib/rails/graphql/helpers/with_assignment.rb

Overview

Helper module that allows other objects to hold an assigned_to object

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(other) ⇒ Object

Add extra instance based methods



9
10
11
12
# File 'lib/rails/graphql/helpers/with_assignment.rb', line 9

def self.extended(other)
  other.delegate :assigned?, :assigned_to, :safe_assigned_class,
    :assigned_class, to: :class
end

Instance Method Details

#assigned?Boolean

Check if the class is assigned

Returns:

  • (Boolean)


15
16
17
# File 'lib/rails/graphql/helpers/with_assignment.rb', line 15

def assigned?
  assigned_to.present?
end

#assigned_classObject

Return the actual class object of the assignment



42
43
44
45
46
47
48
# File 'lib/rails/graphql/helpers/with_assignment.rb', line 42

def assigned_class
  @assigned_class ||= begin
    klass = assigned_to.constantize
    validate_assignment!(klass)
    klass
  end
end

#assigned_toObject

Check its own class or pass it to the superclass



26
27
28
# File 'lib/rails/graphql/helpers/with_assignment.rb', line 26

def assigned_to
  (defined?(@assigned_to) && @assigned_to.presence) || superclass.try(:assigned_to)
end

#assigned_to=(value) ⇒ Object

Make sure to always save the assignment as string, so that assigned_class can return the actual object



32
33
34
35
36
37
38
39
# File 'lib/rails/graphql/helpers/with_assignment.rb', line 32

def assigned_to=(value)
  if value.is_a?(Module)
    @assigned_class = value
    @assigned_to = value.name
  else
    @assigned_to = value
  end
end

#register!Object

After a successfully registration, add the assigned class to the type map as a great alias to find the object, but only if the class does not have an alias already



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rails/graphql/helpers/with_assignment.rb', line 60

def register!
  return if abstract?
  return super unless assigned?

  super.tap do
    break unless (klass = safe_assigned_class)
    break if GraphQL.type_map.exist?(klass, namespaces: namespaces)

    GraphQL.type_map.register_alias(klass, gql_name, namespaces: namespaces)
  end
end

#safe_assigned_classObject

Get the assigned class, but if an known exception happens, just ignore



51
52
53
54
55
# File 'lib/rails/graphql/helpers/with_assignment.rb', line 51

def safe_assigned_class
  assigned_class
rescue ::ArgumentError, ::NameError
  # Ignores the possible errors here related
end

#valid_assignment?(value) ⇒ Boolean

Check if the given value is a valid input for the assigned class

Returns:

  • (Boolean)


20
21
22
23
# File 'lib/rails/graphql/helpers/with_assignment.rb', line 20

def valid_assignment?(value)
  assigned? && (klass = safe_assigned_class).present? &&
    ((value.is_a?(Module) && value <= klass) || value.is_a?(klass))
end