Module: HQ::GraphQL::Ext::EnumExtensions

Defined in:
lib/hq/graphql/ext/enum_extensions.rb

Instance Method Summary collapse

Instance Method Details

#default_model_nameObject



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

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

#lazy_load(&block) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/hq/graphql/ext/enum_extensions.rb', line 59

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

#lazy_load!Object



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

def lazy_load!
  lazy_load.shift.call while lazy_load.length > 0
  @lazy_load = []
end

#with_model(klass = default_model_name.safe_constantize, prefix: nil, register: true, scope: nil, strip: /(^[^_a-zA-Z])|([^_a-zA-Z0-9]*)/, 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)


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

def with_model(
  klass = default_model_name.safe_constantize,
  prefix: nil,
  register: true,
  scope: nil,
  strip: /(^[^_a-zA-Z])|([^_a-zA-Z0-9]*)/,
  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).gsub(strip, "")}", value: record
    end
  end
end