Class: HQ::GraphQL::Enum

Inherits:
GraphQL::Schema::Enum
  • Object
show all
Defined in:
lib/hq/graphql/enum.rb

Direct Known Subclasses

SortBy, SortOrder

Defined Under Namespace

Classes: SortBy, SortOrder

Class Method Summary collapse

Class Method Details

.default_model_nameObject



73
74
75
# File 'lib/hq/graphql/enum.rb', line 73

def self.default_model_name
  to_s.sub(/^((::)?\w+)::/, "")
end

.lazy_load(&block) ⇒ Object



57
58
59
60
61
# File 'lib/hq/graphql/enum.rb', line 57

def self.lazy_load(&block)
  @lazy_load ||= []
  @lazy_load << block if block
  @lazy_load
end

.lazy_load!Object



63
64
65
66
# File 'lib/hq/graphql/enum.rb', line 63

def self.lazy_load!
  lazy_load.map(&:call)
  @lazy_load = []
end

.to_graphqlObject



68
69
70
71
# File 'lib/hq/graphql/enum.rb', line 68

def self.to_graphql
  lazy_load!
  super
end

.with_model(klass = default_model_name.safe_constantize, prefix: nil, register: true, scope: nil, value_method: :name) ⇒ Object

Auto generate enums from the database using ActiveRecord

This comes in handy when we have constants that we want represented as enums.

Example

 Let's assume we're saving data into a user types table
   # select * from user_types;
    id |    name
   --- +-------------
    1  | Admin
    2  | Support User
   (2 rows)

```ruby
  class Enums::UserType < ::HQ::GraphQL::Enum
    with_model
  end
```

Creates the following enum:
```graphql
  enum UserType {
    Admin
    SupportUser
  }
```

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/hq/graphql/enum.rb', line 32

def self.with_model(
  klass = default_model_name.safe_constantize,
  prefix: nil,
  register: true,
  scope: nil,
  value_method: :name
)
  raise ArgumentError.new(<<~ERROR) if !klass
    `::HQ::GraphQL::Enum.with_model {...}' had trouble automatically inferring the class name.
    Avoid this by manually passing in the class name: `::HQ::GraphQL::Enum.with_model(#{default_model_name}) {...}`
  ERROR

  if register
    ::HQ::GraphQL.enums << klass
    ::HQ::GraphQL::Types.register(klass, self)
  end

  lazy_load do
    records = scope ? klass.instance_exec(&scope) : klass.all
    records.each do |record|
      value "#{prefix}#{record.send(value_method).delete(" ")}", value: record
    end
  end
end