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.