Sha256: 6b69ec231149c59cc84a8e792f41515258d0359e15c761b8009ff6c5e171da47

Contents?: true

Size: 1.79 KB

Versions: 2

Compression:

Stored size: 1.79 KB

Contents

# encoding: utf-8

module Hyperdrive
  class Resource
    attr_reader :endpoint, :allowed_params, :filters, :request_handlers
    attr_accessor :name, :desc

    def initialize(key)
      @key = key
      @endpoint = "/#{@key.to_s.en.plural}"
      @allowed_params = default_allowed_params
      @filters = default_filters
      @request_handlers = default_request_handlers
    end

    def register_param(key, description, options = {})
      options = default_param_options.merge(options)
      @allowed_params[key] = { desc: description }.merge(options)
    end

    def register_filter(key, description, options = {})
      options = default_filter_options.merge(options)
      @filters[key] = { desc: description }.merge(options)
    end

    def define_request_handler(request_method, block)
      @request_handlers[request_method] = block
      if request_method == :get
        @request_handlers[:head] = block
      end
    end

    def request_handler(http_request_method)
      request_method = Hyperdrive::Values.request_methods_string_map[http_request_method]
      request_handlers[request_method]
    end

    def request_method_allowed?(http_request_method)
      allowed_methods.include?(http_request_method)
    end

    def allowed_methods
      Hyperdrive::Values.request_methods_symbol_map.values_at(*request_handlers.keys)
    end

    private

    def default_allowed_params
      {
        id: { desc: 'Resource Identifier', required: %w(PUT PATCH DELETE) }
      }
    end

    def default_param_options
      { required: true }.freeze
    end

    def default_filters
      {
        id: { desc: 'Resource Identifier', required: false }
      }
    end

    def default_filter_options
      { required: false }.freeze
    end

    def default_request_handlers
      { options: proc { '' } }
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hyperdrive-0.0.5 lib/hyperdrive/resource.rb
hyperdrive-0.0.4 lib/hyperdrive/resource.rb