aboutsummaryrefslogtreecommitdiffstats
path: root/app/controllers/apidocs_controller.rb
blob: c9a8da8fcf3903317ef0b7b13aab3b4b71f36f08 (plain)
1
2
3
4
5
6
7
8
9
10
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
37
38
39
40
41
42
43
44
45
46
47
class ApidocsController < ApplicationController
  before_action :reload_docs

  def index
    @routes = @@routes
  end

  def endpoint
    @routes = @@routes

    method = @@routes[params[:method]]
    unless method
      raise Aclog::Exceptions::DocumentNotFound
    end

    @resource = method[params[:namespace]]
    unless @resource
      raise Aclog::Exceptions::DocumentNotFound
    end

    @endpoint = @resource[params[:path]]
    unless @endpoint
      raise Aclog::Exceptions::DocumentNotFound
    end

    if @endpoint.route_example_params
      @example_request_uri = root_url + "api" + @endpoint.route_path.sub(/\(\.:format\)$/, ".json")
      @example_request_uri += "?" + @endpoint.route_example_params.to_param
    end
  end

  private
  def reload_docs
    @@routes ||= begin
      h = {}
      Api.routes.reject {|r| r.route_ignore }.each {|route|
        next if route.route_method == "HEAD"
        # /tweets/show(.:format) -> tweets, show
        method = route.route_method.downcase
        namespace = route.route_namespace[1..-1]
        path = route.route_path.sub(route.route_namespace, "")[1..-11] # 10: "(.:format)".size
        ((h[method] ||= {})[namespace] ||= {})[path] = route
      }
      h
    end
  end
end