Sha256: 688c4c2e9720125a9a71ae583876a1dcc3de34016d014e83512bcdb9411a3fc6

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

require_relative "../dsl"
require_relative "./operation"

module Swagger
  class DSL < Hash
    module RailsController
      class NotMatch < StandardError; end
      class NotExactMatch < StandardError; end

      def swagger(action, format = :json, path: nil, method: nil, &block)
        if Swagger::DSL.current.config.lazy_define_paths
          Swagger::DSL.current.define_paths_procs <<
            -> { swagger_define_path(action, format, path: path, method: method, &block) }
        else
          swagger_define_path(action, format, path: path, method: method, &block)
        end
      end

      def swagger_define_path(action, format = :json, path: nil, method: nil, &block)
        defaults = { action: action.to_s, controller: name.underscore.sub(/_controller$/, "") }
        route = Rails.application.routes.routes.routes.find { |r| r.required_defaults == defaults }
        unless route
          raise NotMatch,
                "route not found! specify additional :path and :method key like { path: '/foos/{id}', method: 'get'}"
        end
        method ||= route.verb.downcase
        if method.include?("|")
          raise NotExactMatch, "route matched but verb can be #{verb}! specify :method key like 'get'."
        end

        method = %w[put patch] if %w[put patch].include?(method)
        path ||= route.path.spec.to_s.sub("(.:format)", "").gsub(/:(\w+)/, "{\\1}")

        Swagger::DSL.current["paths"][path] ||= {}
        Array(method).each do |single_method|
          Swagger::DSL.current["paths"][path][single_method] = Swagger::DSL::Operation.new("#{name}##{action}.#{single_method}", format: format, &block)
        end
      end

      alias_method :oas3, :swagger
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
swagger-dsl-2.0.5 lib/swagger/dsl/rails_controller.rb