ruby-on-railsgraphqlgraphql-ruby

How to use rails Helpers in graphql?


How can I use Helpers from /app/helpers directory in my /app/graphql directory? For example there is a data type which is a nested JSON Object and I got a JSON Schema file which describes the structure of it. There also is a JsonSchemaHelper which I would like to use to validate a Scalar type against the JSON schema. like that:

class Types::Scalar::Node < Types::Base::BaseScalar
  def self.coerce_input(value, _context)
    if Validators::GraphqlValidator.is_parsable_json?(value)
      value = JSON.parse(value)
    end
    Validators::Node.validate!(value)
    value
  end

  #Validators could be used to check if it fit the client-side declared type
  def self.coerce_result(value, _context)
    Validators::Node.validate!(value)
    value
  end
end

and the validator looks like:

module Validators
  class Node
    include JsonSchemaHelper
    def self.validate!(ast)
      json_schema_validate('Node', ast)
    end
  end
end

the include JsonSchemaHelper doesn't work.


Solution

  • include adds methods of JsonSchemaHelper as instance methods of Validators::Node class. self.validate!(ast) is a class method and you try to call json_schema_validate as a class method. Change include JsonSchemaHelper to extend JsonSchemaHelper.