Module: Ruil::Register

Defined in:
lib/ruil/register.rb

Overview

Ruil::Register module allow us to register resources. When a Ruil::Resource object is created it is automatically registered using the register method. The call method answer a request with the first registered resource that match the request. Matches are checked using the order of resource registrations.

Constant Summary collapse

@@resources =
{
  'GET'    => [],
  'POST'   => [],
  'PUT'    => [],
  'DELETE' => []
}

Class Method Summary collapse

Class Method Details

.<<(resource) ⇒ Object

Register a resource.



17
18
19
20
21
# File 'lib/ruil/register.rb', line 17

def self.<<(resource)
  resource.request_methods.each do |request_method|
    @@resources[request_method] << resource
  end
end

.call(request_or_env) ⇒ Rack::Response

Answer a request with the response of the matched resource for that request.

Parameters:

  • request_or_env (Rack::Request, Hash)

    the request.

Returns:

  • (Rack::Response)

    the response to the request.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ruil/register.rb', line 27

def self.call(request_or_env)
  case request_or_env
  when Rack::Request
    request = request_or_env
  when Hash
    request = Rack::Request.new(request_or_env)
  else
    raise "Invalid request: #{request_or_env.inspect}"
  end
  @@resources[request.request_method].each do |resource|
    response = resource.call(request)
    return response if response
  end
  [401, {'Content-Type' => 'plain/text'}, ["Resource not found: #{request.url}"]]
end