Class: LowLoop

Inherits:
Object
  • Object
show all
Includes:
Observers
Defined in:
lib/low_loop.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config:, dependencies: []) ⇒ LowLoop

Returns a new instance of LowLoop.



18
19
20
21
22
23
24
25
26
# File 'lib/low_loop.rb', line 18

def initialize(config:, dependencies: [])
  @config = config

  dependencies.each do |dependency|
    observers << dependency
  end

  observers.push(self, action: :mirror) if config.mirror_mode
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



16
17
18
# File 'lib/low_loop.rb', line 16

def config
  @config
end

Instance Method Details

#==(other) ⇒ Object

Consider LowLoop a value object in the context of Observers (there can only be one).



68
# File 'lib/low_loop.rb', line 68

def ==(other) = other.class == self.class

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


69
# File 'lib/low_loop.rb', line 69

def eql?(other) = self == other

#hashObject



70
# File 'lib/low_loop.rb', line 70

def hash = [self.class].hash

#mirror(event:) ⇒ Object

Fallback mode for when there’s no dependencies and you want to know that the server is still working.



61
62
63
64
65
# File 'lib/low_loop.rb', line 61

def mirror(event:)
  request = event.request
  response = Low::Factories::ResponseFactory.html(body: "Thank you for visiting #{request.path} with body: '#{request.body}'")
  Low::Events::ResponseEvent.new(response:)
end

#startObject



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

def start
  server = start_server

  Fiber.set_scheduler(Async::Scheduler.new)

  Fiber.schedule do
    loop do
      socket = server.accept

      Fiber.schedule do
        request = Low::RequestParser.parse(socket:, host: config.host, port: config.port)
        response_event = take(event: Low::Events::RequestEvent.new(request:))
        response = response_event.response

        Low::ResponseBuilder.respond(config:, socket:, response:)
      rescue StandardError => e
        puts e.message
      ensure
        socket&.close
      end
    end
  end
end

#start_serverObject



52
53
54
55
56
57
58
# File 'lib/low_loop.rb', line 52

def start_server
  puts "Starting server @ #{config.host}:#{config.port}" unless config.matrix_mode

  server = TCPServer.new(config.host, config.port)
  server.listen(10)
  server
end