Hello everybody!
I'm using graphql-ruby with Rails API mode.
Is there a possibility to extract fields from query_type.rb/mutation_type.rb so you don't have one big file where all your fields are defined?
Like some kind of module where you define related fields and this module get included then in your query_type.rb.
Right now i didn't find anything regarding that in the documentation.
This could help to keep your code more organized.
For example from this:
class Types::QueryType < Types::BaseObject
field :show_post, ....
field :all_posts, ....
field :update_post, ...
field :delete_post, ....
field :all_categories, ....
field :show_category, ....
field :update_category, ...
field :delete_category, ....
...and so on
end
to something like this:
class Types::QueryType < Types::BaseObject
include PostFields
include CategoryFields
...and so on
end
If this isn't possible yet, maybe it would be a nice enhancement. What do you think @rmosolgo?
Thanks for your efforts in advance! :-)
Since you're using Rails you could use ActiveSupport::Concern e.g.
module PostFields
extend ActiveSupport::Concern
included do
field :posts, [Post], null: false
end
def posts
Posts.all
end
end
class Types::QueryType < Types::BaseObject
include PostFields
end
Ah thanks @jturkel,
that did the trick!
At first i tried to extract that stuff in a plain module. Like
module PostFields
field :posts, [Post], null: false
def posts
Posts.all
end
end
class Types::QueryType < Types::BaseObject
include PostFields
end
But I didn't think it through correctly, and Ruby complained about a missing "field" method. The evaluation in the context of the class was wrong, which i later recognized.
After reading about concerns, I found another solution too, which I want to leave here, if somebody doesn't want to / can't use concerns:
module PostFields
def self.included(mod)
mod.class_eval do
field :posts, [Post], null: false
def posts
Posts.all
end
end
end
end
class Types::QueryType < Types::BaseObject
include PostFields
end
Most helpful comment
Since you're using Rails you could use
ActiveSupport::Concerne.g.