Class: Ruil::StaticResource

Inherits:
Object
  • Object
show all
Defined in:
lib/ruil/static_resource.rb

Overview

StaticResource objects answer requests with static files.

Instance Method Summary collapse

Constructor Details

#initialize(authorizer = nil) {|_self| ... } ⇒ StaticResource

Initialize a new Ruil::StaticResource.

Parameters:

  • authorizer (lambda(Ruil::Request)) (defaults to: nil)

    A procedure that checks if the user is allowed to access the resource.

Yields:

  • (_self)

Yield Parameters:



15
16
17
18
19
20
21
22
# File 'lib/ruil/static_resource.rb', line 15

def initialize(authorizer = nil, &block)
  # Setup
  @authorizer = authorizer
  @files = {}
  yield self if block_given?
  # Register
  Ruil::Register << self
end

Instance Method Details

#add(file_name, file_uri, content_type) ⇒ Object

Add a static file

Parameters:

  • file_name (String)

    the path in the file system.

  • file_uri (String)

    the path from client request.

  • content_type (String)

    the mime type.



36
37
38
39
40
41
42
43
44
# File 'lib/ruil/static_resource.rb', line 36

def add(file_name, file_uri, content_type)
  file = File.new(file_name)
  body = file.read
  file.close
  @files[file_uri] = {
    :body => [body],
    :content_type => content_type
  }
end

#call(rack_request) ⇒ Rack::Response

Respond a request

Parameters:

  • request (Rack::Request)

    a request to the resource.

Returns:

  • (Rack::Response)

    a response for the request.



50
51
52
53
54
55
56
57
58
59
# File 'lib/ruil/static_resource.rb', line 50

def call(rack_request)
  path_info = rack_request.path_info
  file = @files[path_info]
  return false if file.nil?
  unless @authorizer.nil?
    request = Ruil::Request.new(rack_request)
    return @autorizer.unauthorized unless @authorizer.authorize(request)
  end
  Rack::Response.new(file[:body], 200, {'Content-Type' => file[:content_type]})
end

#request_methodsArray<String>

Methods that a resource responds.

Returns:

  • (Array<String>)


27
28
29
# File 'lib/ruil/static_resource.rb', line 27

def request_methods
  ['GET']
end