Class: LowLoop

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

Constant Summary collapse

DEFAULT_KEEP_ALIVE_TIMEOUT =
30
DEFAULT_REQUEST_TIMEOUT =
10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config:, router: nil, renderer: nil, show_output: true) ⇒ LowLoop

Returns a new instance of LowLoop.



25
26
27
28
29
30
31
32
33
34
# File 'lib/low_loop.rb', line 25

def initialize(config:, router: nil, renderer: nil, show_output: true)
  @config = config
  @frame = LowFrame.new(renderer:, fps: 10, show_output:)

  Low::Events::RequestEvent.define do |observers|
    observers << Low::FileServer.new(web_root: config.web_root, content_types: config.content_types)
    observers << router if router
    observers.push(self, action: :mirror) if config.mirror_mode
  end
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



23
24
25
# File 'lib/low_loop.rb', line 23

def config
  @config
end

Instance Method Details

#==(other) ⇒ Object

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



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

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

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


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

def eql?(other) = self == other

#hashObject



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

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.



80
81
82
83
84
# File 'lib/low_loop.rb', line 80

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

#renderObject



71
72
73
74
75
76
77
# File 'lib/low_loop.rb', line 71

def render
  Async do
    loop do
      @frame.render
    end
  end
end

#startObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/low_loop.rb', line 36

def start
  server = start_server

  Async do |task|
    # Background task.
    task.async do
      loop do
        @frame.render if @frame.renderer
        sleep 0.1 # 10fps
      end
    end

    # Request handler.
    loop do
      socket = server.accept

      task.async do
        handle_connection(socket)
      rescue StandardError => e
        render_error(e)
      ensure
        socket&.close
      end
    end
  end
end

#start_serverObject



63
64
65
66
67
68
69
# File 'lib/low_loop.rb', line 63

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