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.



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

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(action: :mirror) if config.mirror_mode
  end
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



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

def config
  @config
end

Instance Method Details

#==(other) ⇒ Object

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



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

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

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


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

def eql?(other) = self == other

#hashObject



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

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.



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

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



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

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

#startObject



35
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
# File 'lib/low_loop.rb', line 35

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
        puts e.message
      ensure
        socket&.close
      end
    end
  end
end

#start_serverObject



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

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