George Claghorn

graphql-rails-namespace

In Namespacing GraphQL constants in Rails apps, I demonstrated how to nest constants defined in a Rails app’s app/graphql/ directory under a top-level ApplicationGraph module with a little bit of configuration.

I extracted the necessary configuration to a tiny Rails plugin and released it as a gem named graphql-rails-namespace. Now all that’s needed, more or less, is bundle add graphql-rails-namespace.

The gem is released under the terms of the MIT License, and the source code is available on GitHub. See the README for more details.

Namespacing GraphQL constants in Rails apps

Update: I’ve extracted the configuration described in this post to a Rails plugin named graphql-rails-namespace. You should use the plugin instead, but I’ll leave this post up for posterity.

The GraphQL Ruby library encourages placing GraphQL modules and classes such as type definitions under the app/graphql/ directory in Rails applications. Here’s an example from the GraphQL Ruby homepage:

# app/graphql/types/profile_type.rb
class Types::ProfileType < Types::BaseObject
  field :id, ID, null: false
  field :name, String, null: false
  field :avatar, Types::PhotoType
end

Because Rails treats all subdirectories of app as root directories for the purpose of autoloading, classes in app/graphql/types/ are nested in a top-level Types module. In the above example, app/graphql/types/profile_type.rb defines Types::ProfileType. But Types is too general a top-level namespace for GraphQL type definitions. The GraphQL schema class defined in app/graphql/schema.rb is named Schema, but it’s specifically a GraphQL schema, not a generic schema. It would be nice to nest GraphQL-specific modules and classes in a GraphQL-specific namespace.

Keep reading…