Module: SoberSwag::Controller::ClassMethods

Defined in:
lib/sober_swag/controller.rb

Overview

Module containing class methods. Any class that includes SoberSwag::Controller will also extend ClassMethods.

Instance Method Summary collapse

Instance Method Details

#define(method, action, path, &block) ⇒ Object

TODO:

Explore parsing the path parameter from rails routes so we can avoid forcing the duplicate boilerplate.

Define a new action with the given HTTP method, action name, and path. This will eventually delegate to making an actual method on your controller, so you can use controllers as you wish with no harm.

This method takes a block, evaluated in the context of a Route. Used like:

define(:get, :show, '/posts/{id}') do
  path_params do
    attribute :id, Types::Integer
  end
  action do
    @post = Post.find(parsed_path.id)
    render json: @post
  end
end

This will define an "action module" on this class to contain the generated types. In the above example, the following constants will be defined on the controller:

  • PostsController::Show - the container module for everything in this action
  • PostsController::Show::PathParams - the dry-struct type for the path attribute.

So, in the same controller, you can refer to Show::PathParams to get the type created by the 'path_params' block above.

The block given evaluates in the context of SoberSwag::Controller::Route.

Parameters:

  • method (Symbol)

    the HTTP method of this route

  • action (Symbol)

    the name of the controller method this maps onto

  • path (String)

    an OpenAPI v3 Path Specifier



58
59
60
61
62
63
# File 'lib/sober_swag/controller.rb', line 58

def define(method, action, path, &block)
  r = Route.new(method, action, path)
  r.instance_eval(&block)
  const_set(r.action_module_name, r.action_module)
  defined_routes << r
end

#defined_routesArray<SoberSwag::Controller::Route>

All the routes that this controller knows about.



68
69
70
# File 'lib/sober_swag/controller.rb', line 68

def defined_routes
  @defined_routes ||= []
end

#find_route(name) ⇒ SoberSwag::Controller::Route

Find a route with the given name.

Parameters:

  • name (Symbol)

    the name

Returns:



76
77
78
# File 'lib/sober_swag/controller.rb', line 76

def find_route(name)
  defined_routes.find { |r| r.action_name.to_s == name.to_s }
end

#swagger_infoHash

Get the OpenAPI v3 definition for this controller.

Returns:

  • (Hash)


84
85
86
87
88
89
90
91
92
93
# File 'lib/sober_swag/controller.rb', line 84

def swagger_info
  @swagger_info ||=
    begin
      res = defined_routes.reduce(SoberSwag::Compiler.new) { |c, r| c.add_route(r) }
      {
        openapi: '3.0.0',
        info: { version: '1', title: name }
      }.merge(res.to_swagger)
    end
end