Class: Ruflet::Rails::Protocol::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/ruflet/rails/protocol/middleware.rb

Overview

Rack middleware inserted before ActionDispatch::Static by the Railtie.

Responsibilities:

1. WebSocket at ws_path (/ws) — native mobile/desktop clients.
2. WebSocket at the build dir base path (e.g. /app, /app/) — the
   Flutter web client uses Uri.base from <base href="/app/"> as its
   connection URL, so it naturally connects back to /app/ as WebSocket.
   No URL injection needed — the client finds the server on its own.
3. Block direct HTTP access to the build dir's index so
   ActionDispatch::Static never leaks it at /app — serves Rails' 404.

Constant Summary collapse

INDEX_SUFFIXES =
["", "/", "/index.html"].freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



19
20
21
22
# File 'lib/ruflet/rails/protocol/middleware.rb', line 19

def initialize(app)
  @app         = app
  @ws_endpoint = nil
end

Instance Method Details

#call(env) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ruflet/rails/protocol/middleware.rb', line 24

def call(env)
  cfg  = Ruflet::Rails.config
  path = env["PATH_INFO"].to_s

  if cfg.app_file
    # WS at configured ws_path — native/desktop clients
    if cfg.ws_path && path == normalize(cfg.ws_path) && websocket_upgrade?(env)
      return Context.with_env(env) { ws_endpoint(cfg).call(env) }
    end

    # WS at build dir base path — Flutter web client (Uri.base = /app/)
    if cfg.web_build_dir && build_dir_base?(path, cfg.web_build_dir.to_s) && websocket_upgrade?(env)
      return Context.with_env(env) { ws_endpoint(cfg).call(env) }
    end
  end

  # Block direct HTTP access to the build dir index
  if cfg.web_build_dir && build_dir_index?(path, cfg.web_build_dir.to_s)
    return rails_404
  end

  Context.with_env(env) { @app.call(env) }
end