Module: GraphQLDocs::Helpers

Included in:
App, Generator, Parser, Renderer
Defined in:
lib/graphql-docs/helpers.rb

Overview

Helper methods module for use in ERB templates.

This module provides utility methods that can be called from within ERB templates when generating documentation. Methods are available via dot notation in templates, such as <%= slugify.(text) %>.

Examples:

Using helper methods in templates

<%= slugify.("My Type Name") %> # => "my-type-name"
<%= markdownify.("**bold text**") %> # => "<strong>bold text</strong>"

Constant Summary collapse

SLUGIFY_PRETTY_REGEXP =

Regular expression for slugifying strings in a URL-friendly way. Matches all characters that are not alphanumeric or common URL-safe characters.

Regexp.new("[^[:alnum:]._~!$&'()+,;=@]+").freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#templatesHash

Returns Cache of loaded ERB templates for includes.

Returns:

  • (Hash)

    Cache of loaded ERB templates for includes



24
25
26
# File 'lib/graphql-docs/helpers.rb', line 24

def templates
  @templates
end

Instance Method Details

#emojify(string) ⇒ Object

Converts emoji shortcodes like :smile: to emoji characters



88
89
90
91
92
93
# File 'lib/graphql-docs/helpers.rb', line 88

def emojify(string)
  string.gsub(/:([a-z0-9_+-]+):/) do |match|
    emoji = Emoji.find_by_alias(Regexp.last_match(1))
    emoji ? emoji.raw : match
  end
end

#graphql_directive_typesArray<Hash>

Returns all directive types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of directive hashes with locations and arguments



168
169
170
# File 'lib/graphql-docs/helpers.rb', line 168

def graphql_directive_types
  @parsed_schema[:directive_types] || []
end

#graphql_enum_typesArray<Hash>

Returns all enum types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of enum type hashes with values



140
141
142
# File 'lib/graphql-docs/helpers.rb', line 140

def graphql_enum_types
  @parsed_schema[:enum_types] || []
end

#graphql_input_object_typesArray<Hash>

Returns all input object types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of input object type hashes



154
155
156
# File 'lib/graphql-docs/helpers.rb', line 154

def graphql_input_object_types
  @parsed_schema[:input_object_types] || []
end

#graphql_interface_typesArray<Hash>

Returns all interface types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of interface type hashes



133
134
135
# File 'lib/graphql-docs/helpers.rb', line 133

def graphql_interface_types
  @parsed_schema[:interface_types] || []
end

#graphql_mutation_typesArray<Hash>

Returns all mutation types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of mutation hashes with input and return fields



119
120
121
# File 'lib/graphql-docs/helpers.rb', line 119

def graphql_mutation_types
  @parsed_schema[:mutation_types] || []
end

#graphql_object_typesArray<Hash>

Returns all object types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of object type hashes



126
127
128
# File 'lib/graphql-docs/helpers.rb', line 126

def graphql_object_types
  @parsed_schema[:object_types] || []
end

#graphql_operation_typesArray<Hash>

Returns all operation types (Query, Mutation) from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of operation type hashes



105
106
107
# File 'lib/graphql-docs/helpers.rb', line 105

def graphql_operation_types
  @parsed_schema[:operation_types] || []
end

#graphql_query_typesArray<Hash>

Returns all query types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of query hashes with fields and arguments



112
113
114
# File 'lib/graphql-docs/helpers.rb', line 112

def graphql_query_types
  @parsed_schema[:query_types] || []
end

#graphql_root_typesHash

Returns the root types (query, mutation) from the parsed schema.

Returns:

  • (Hash)

    Hash containing 'query' and 'mutation' keys with type names



98
99
100
# File 'lib/graphql-docs/helpers.rb', line 98

def graphql_root_types
  @parsed_schema[:root_types] || []
end

#graphql_scalar_typesArray<Hash>

Returns all scalar types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of scalar type hashes



161
162
163
# File 'lib/graphql-docs/helpers.rb', line 161

def graphql_scalar_types
  @parsed_schema[:scalar_types] || []
end

#graphql_union_typesArray<Hash>

Returns all union types from the parsed schema.

Returns:

  • (Array<Hash>)

    Array of union type hashes with possible types



147
148
149
# File 'lib/graphql-docs/helpers.rb', line 147

def graphql_union_types
  @parsed_schema[:union_types] || []
end

#include(filename, opts = {}) ⇒ String

Includes and renders a partial template file.

This method loads an ERB template from the includes directory and renders it with the provided options. Useful for reusing template fragments.

Examples:

In an ERB template

<%= include.("field_table.html", fields: type[:fields]) %>

Parameters:

  • filename (String)

    Name of the template file in the includes directory

  • opts (Hash) (defaults to: {})

    Options to pass to the template

Returns:

  • (String)

    Rendered HTML content from the template



51
52
53
54
55
# File 'lib/graphql-docs/helpers.rb', line 51

def include(filename, opts = {})
  template = fetch_include(filename)
  opts = {base_url: @options[:base_url], classes: @options[:classes]}.merge(opts)
  template.result(OpenStruct.new(opts.merge(helper_methods)).instance_eval { binding })
end

#markdownify(string) ⇒ String

Converts a Markdown string to HTML.

Examples:

markdownify("**bold**") # => "<strong>bold</strong>"
markdownify(nil) # => ""

Parameters:

  • string (String)

    Markdown content to convert

Returns:

  • (String)

    HTML output from the Markdown, empty string if input is nil



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/graphql-docs/helpers.rb', line 65

def markdownify(string)
  return "" if string.nil?

  begin
    # Replace emoji shortcodes before markdown processing
    string_with_emoji = emojify(string)

    doc = ::Commonmarker.parse(string_with_emoji)
    html = if @options[:pipeline_config][:context][:unsafe]
      doc.to_html(options: {render: {unsafe: true}})
    else
      doc.to_html
    end
    html.strip
  rescue => e
    # Log error and return safe fallback
    warn "Failed to parse markdown: #{e.message}"
    require "cgi" unless defined?(CGI)
    CGI.escapeHTML(string)
  end
end

#slugify(str) ⇒ String

Converts a string into a URL-friendly slug.

Examples:

slugify("My Type Name") # => "my-type-name"
slugify("Author.firstName") # => "author.firstname"

Parameters:

  • str (String)

    The string to slugify

Returns:

  • (String)

    Lowercase slug with hyphens instead of spaces



34
35
36
37
38
# File 'lib/graphql-docs/helpers.rb', line 34

def slugify(str)
  slug = str.gsub(SLUGIFY_PRETTY_REGEXP, "-")
  slug.gsub!(/^-|-$/i, "")
  slug.downcase
end

#split_into_metadata_and_contents(contents, parse: true) ⇒ Array<(Hash, String), (String, String)>

Splits content into YAML front matter metadata and body content.

Parameters:

  • contents (String)

    Content string potentially starting with YAML front matter

  • parse (Boolean) (defaults to: true)

    Whether to parse the YAML (true) or return it as a string (false)

Returns:

  • (Array<(Hash, String), (String, String)>)

    Tuple of [metadata, content]

Raises:

  • (RuntimeError)

    If YAML front matter format is invalid

  • (RuntimeError)

    If YAML parsing fails

  • (TypeError)

    If parsed YAML is not a Hash



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/graphql-docs/helpers.rb', line 181

def (contents, parse: true)
  pieces = yaml_split(contents)
  raise "The file '#{content_filename}' appears to start with a metadata section (three or five dashes at the top) but it does not seem to be in the correct format." if pieces.size < 4

  # Parse
  begin
    meta = if parse
      YAML.safe_load(pieces[2]) || {}
    else
      pieces[2]
    end
  rescue Exception => e # rubocop:disable Lint/RescueException
    raise "Could not parse YAML for #{name}: #{e.message}"
  end

  # Validate that parsed YAML is a Hash when parsing is enabled
  if parse && !meta.is_a?(Hash)
    raise TypeError, "Expected YAML front matter to be a hash, got #{meta.class}"
  end

  [meta, pieces[4]]
end

#yaml?(contents) ⇒ Boolean

Checks if content starts with YAML front matter.

Parameters:

  • contents (String)

    Content to check

Returns:

  • (Boolean)

    True if content starts with YAML front matter delimiters



208
209
210
# File 'lib/graphql-docs/helpers.rb', line 208

def yaml?(contents)
  contents =~ /\A-{3,5}\s*$/
end

#yaml_split(contents) ⇒ Array<String>

Splits content by YAML front matter delimiters.

Parameters:

  • contents (String)

    Content to split

Returns:

  • (Array<String>)

    Array of content pieces split by YAML delimiters



216
217
218
# File 'lib/graphql-docs/helpers.rb', line 216

def yaml_split(contents)
  contents.split(/^(-{5}|-{3})[ \t]*\r?\n?/, 3)
end