Sha256: d782b2a2595e96cd0984e168704b8e9fa9c4ea424467d14870accf613cc69045

Contents?: true

Size: 1.43 KB

Versions: 3

Compression:

Stored size: 1.43 KB

Contents

module Dox
  module Entities
    class Action
      attr_reader :name, :desc, :verb, :path, :uri_params
      attr_accessor :examples

      def initialize(name, details, request)
        @request = request
        @name = name
        @desc = details[:action_desc]
        @verb = details[:action_verb] || request.method
        @path = details[:action_path] || template_path
        @uri_params = details[:action_params] || template_path_params
        @examples = []

        validate!
      end

      private

      attr_reader :request

      # /pokemons/1 => pokemons/{id}
      def template_path
        path = request.path.dup.presence || request.fullpath.split("?").first
        path_params.each do |key, value|
          path.sub!(%r{\/#{value}(\/|$)}, "/{#{key}}\\1")
        end
        path
      end

      def path_params
        @path_params ||= request.path_parameters.symbolize_keys.except(:action, :controller, :format)
      end

      def template_path_params
        h = {}
        path_params.each do |param, value|
          param_type = guess_param_type(value)
          h[param] = { type: param_type, required: :required, value: value }
        end
        h
      end

      def guess_param_type(param)
        if param =~ /^\d+$/
          :number
        else
          :string
        end
      end

      def validate!
        raise(Error, "Unrecognized HTTP verb #{verb}") unless Util::Http.verb?(verb)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
dox-1.0.2 lib/dox/entities/action.rb
dox-1.0.1 lib/dox/entities/action.rb
dox-1.0.0 lib/dox/entities/action.rb