DEV Community

André
André

Posted on • Originally published at andreligne.io on

1

GraphQL field names in Ruby

While building a GraphQL API, I noticed that many times the name of the field on the type didn’t match the name of the method on the object.

class Types::UserType < Types::BaseObject
  field :is_active, Boolean, null: false
  field :is_banned, Boolean, null: false

  def is_active
    object.active?
  end

  def is_banned
    object.banned?
  end
end

This caused me to have to write custom methods in the Object type that acts as a proxy for the calling the method.

It turns out there’s a documented way in the graphql-ruby gem that basically does all of this for you - the method attribute.

And by using the method: attribute, we can rewrite our previous example like so:

class Types::UserType < Types::BaseObject
  field :is_active, Boolean, null: false, method: :active?
  field :is_banned, Boolean, null: false, method: :banned?
end

We can now keep writing methods using the usual Ruby conventions but expose them in the schema using names that make sense for the API consumer.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
lostpupil profile image
Crazy_Phage

This is great.