Class: GovukTechDocs::ApiReference::Extension

Inherits:
Middleman::Extension
  • Object
show all
Defined in:
lib/govuk_tech_docs/api_reference/api_reference_extension.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options_hash = {}, &block) ⇒ Extension



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/govuk_tech_docs/api_reference/api_reference_extension.rb', line 11

def initialize(app, options_hash = {}, &block)
  super

  @app = app
  @config = @app.config[:tech_docs]

  # If no api path then just return.
  if @config["api_path"].to_s.empty?
    @api_parser = false
    return
  end

  # Is the api_path a url or path?
  if uri?(@config["api_path"])
    @api_parser = true
    @document = Openapi3Parser.load_url(@config["api_path"])
  elsif File.exist?(@config["api_path"])
    # Load api file and set existence flag.
    @api_parser = true
    @document = Openapi3Parser.load_file(@config["api_path"])
  else
    @api_parser = false
    raise "Unable to load api path from tech-docs.yml"
  end
  @render = Renderer.new(@app, @document)
end

Instance Method Details

#api(text) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/govuk_tech_docs/api_reference/api_reference_extension.rb', line 47

def api(text)
  if @api_parser == true

    keywords = {
      "api>" => "default",
      "api_schema>" => "schema",
    }

    regexp = keywords.map { |k, _| Regexp.escape(k) }.join("|")

    md = text.match(/^<p>(#{regexp})/)
    if md
      key = md.captures[0]
      type = keywords[key]

      text.gsub!(/#{Regexp.escape(key)}\s+?/, "")

      # Strip paragraph tags from text
      text = text.gsub(/<\/?[^>]*>/, "")
      text = text.strip

      if text == "api&gt;"
        @render.api_full(api_info, api_servers)
      elsif type == "default"
        output = @render.path(text)
        # Render any schemas referenced in the above path
        output += @render.schemas_from_path(text)
        output
      else
        @render.schema(text)
      end

    else
      text
    end
  else
    text
  end
end

#uri?(string) ⇒ Boolean



38
39
40
41
42
43
44
45
# File 'lib/govuk_tech_docs/api_reference/api_reference_extension.rb', line 38

def uri?(string)
  uri = URI.parse(string)
  %w[http https].include?(uri.scheme)
rescue URI::BadURIError
  false
rescue URI::InvalidURIError
  false
end