module SoberSwag::Controller::ClassMethods

Module containing class methods. Any class that `include`s {SoberSwag::Controller} will also `extend` {SoberSwag::Controller::ClassMethods}.

Public Instance Methods

define(method, action, path, &block) click to toggle source

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 {SoberSwag::Controller::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`.

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

@param method [Symbol] the HTTP method of this route @param action [Symbol] the name of the controller method this maps onto @param path [String] an OpenAPI v3 Path Specifier

# 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_routes() click to toggle source

All the routes that this controller knows about. @return [Array<SoberSwag::Controller::Route>

# File lib/sober_swag/controller.rb, line 68
def defined_routes
  @defined_routes ||= []
end
find_route(name) click to toggle source

Find a route with the given name. @param name [Symbol] the name @return [SoberSwag::Controller::Route]

# 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_info() click to toggle source

Get the OpenAPI v3 definition for this controller.

@return [Hash]

# 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