Class: Capsium::Reactor

Inherits:
Object
  • Object
show all
Defined in:
lib/capsium/reactor.rb

Constant Summary collapse

DEFAULT_PORT =
8864

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(package:, port: DEFAULT_PORT, do_not_listen: false) ⇒ Reactor

Returns a new instance of Reactor.



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

def initialize(package:, port: DEFAULT_PORT, do_not_listen: false)
  @package = package.is_a?(String) ? Package.new(package) : package
  @package_path = @package.path
  @port = port
  setup_server(do_not_listen)
  @routes = @package.routes
  mount_routes
end

Instance Attribute Details

#packageObject

Returns the value of attribute package.



12
13
14
# File 'lib/capsium/reactor.rb', line 12

def package
  @package
end

#package_pathObject

Returns the value of attribute package_path.



12
13
14
# File 'lib/capsium/reactor.rb', line 12

def package_path
  @package_path
end

#portObject

Returns the value of attribute port.



12
13
14
# File 'lib/capsium/reactor.rb', line 12

def port
  @port
end

#routesObject

Returns the value of attribute routes.



12
13
14
# File 'lib/capsium/reactor.rb', line 12

def routes
  @routes
end

#serverObject

Returns the value of attribute server.



12
13
14
# File 'lib/capsium/reactor.rb', line 12

def server
  @server
end

#server_threadObject

Returns the value of attribute server_thread.



12
13
14
# File 'lib/capsium/reactor.rb', line 12

def server_thread
  @server_thread
end

Instance Method Details

#handle_request(request, response) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/capsium/reactor.rb', line 29

def handle_request(request, response)
  route = @routes.resolve(request.path)
  if route
    target = route.target
    content_path = target.fs_path(@package.manifest)
    if File.exist?(content_path)
      response.status = 200
      response["Content-Type"] = target.mime(@package.manifest)
      response.body = File.read(content_path)
    else
      response.status = 404
      response["Content-Type"] = "text/plain"
      response.body = "Not Found"
    end
  else
    response.status = 404
    response["Content-Type"] = "text/plain"
    response.body = "Not Found"
  end
end

#serveObject



24
25
26
27
# File 'lib/capsium/reactor.rb', line 24

def serve
  @server_thread = start_server
  start_listener
end