Class: Tina4::WebSocketRoute

Inherits:
Object
  • Object
show all
Defined in:
lib/tina4/router.rb

Overview

A registered WebSocket route with path pattern matching (reuses Route's compile logic)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, handler, auth_required: false) ⇒ WebSocketRoute

Returns a new instance of WebSocketRoute.



291
292
293
294
295
296
297
298
# File 'lib/tina4/router.rb', line 291

def initialize(path, handler, auth_required: false)
  @path = normalize_path(path).freeze
  @handler = handler
  @auth_required = auth_required
  @param_names = []
  @path_regex = compile_pattern(@path)
  @param_names.freeze
end

Instance Attribute Details

#auth_requiredObject

PUBLIC by default (mirrors GET). Flip to true with #secure (or via Tina4.secure_websocket) to require a valid JWT on the upgrade. Mirrors the HTTP Route's auth_required so the upgrade path enforces it identically.



289
290
291
# File 'lib/tina4/router.rb', line 289

def auth_required
  @auth_required
end

#handlerObject (readonly)

Returns the value of attribute handler.



285
286
287
# File 'lib/tina4/router.rb', line 285

def handler
  @handler
end

#param_namesObject (readonly)

Returns the value of attribute param_names.



285
286
287
# File 'lib/tina4/router.rb', line 285

def param_names
  @param_names
end

#pathObject (readonly)

Returns the value of attribute path.



285
286
287
# File 'lib/tina4/router.rb', line 285

def path
  @path
end

#path_regexObject (readonly)

Returns the value of attribute path_regex.



285
286
287
# File 'lib/tina4/router.rb', line 285

def path_regex
  @path_regex
end

Instance Method Details

#match?(request_path) ⇒ Boolean

Returns params hash if matched, false otherwise

Returns:

  • (Boolean)


314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/tina4/router.rb', line 314

def match?(request_path)
  match = @path_regex.match(request_path)
  return false unless match

  if @param_names.empty?
    {}
  else
    params = {}
    @param_names.each_with_index do |param_def, i|
      raw_value = match[i + 1]
      # Same ASCII-8BIT -> UTF-8 relabel as the HTTP Route matcher above,
      # so a WS path param binds to SQL as TEXT (not a BLOB).
      raw_value = raw_value.dup.force_encoding(Encoding::UTF_8) if raw_value.is_a?(::String)
      params[param_def[:name]] = raw_value
    end
    params
  end
end

#no_authObject

Opt back out (the default). Returns self for chaining.



308
309
310
311
# File 'lib/tina4/router.rb', line 308

def no_auth
  @auth_required = false
  self
end

#secureObject

Mark this WebSocket route as requiring bearer-token auth on the upgrade. Returns self for chaining: Tina4::Router.websocket("/chat") { ... }.secure



302
303
304
305
# File 'lib/tina4/router.rb', line 302

def secure
  @auth_required = true
  self
end