Today I Learned

hashrocket A Hashrocket project

Alias Method on a GraphQL Field

A lot of times I find I have to alias a method on a model when I'm exposing it on a GraphQL type. Most often I have to do this with ? methods:

class Post < ApplicationRecord
  def draft?
    ...
  end
end

class PostType < GraphQL::Schema::Object
  field :draft, Boolean, null: false

  def draft
    @object.draft?
  end
end

I want the field to be draft (without the ?), but on it's own the GraphQL Ruby gem can't resolve it to draft?, so I have to add an additional def in the Type class. This works, but it feels clunky.

Turns out you can use the method: option on the field to alias it inline, which I think streamlines things:

class PostType < GraphQL::Schema::Object
  field :draft, Boolean, null: false, method: :draft?
end

Docs

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.