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.



321
322
323
324
325
326
327
328
# File 'lib/tina4/router.rb', line 321

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.



319
320
321
# File 'lib/tina4/router.rb', line 319

def auth_required
  @auth_required
end

#handlerObject (readonly)

Returns the value of attribute handler.



315
316
317
# File 'lib/tina4/router.rb', line 315

def handler
  @handler
end

#param_namesObject (readonly)

Returns the value of attribute param_names.



315
316
317
# File 'lib/tina4/router.rb', line 315

def param_names
  @param_names
end

#pathObject (readonly)

Returns the value of attribute path.



315
316
317
# File 'lib/tina4/router.rb', line 315

def path
  @path
end

#path_regexObject (readonly)

Returns the value of attribute path_regex.



315
316
317
# File 'lib/tina4/router.rb', line 315

def path_regex
  @path_regex
end

Instance Method Details

#match?(request_path) ⇒ Boolean

Returns params hash if matched, false otherwise

Returns:

  • (Boolean)


344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/tina4/router.rb', line 344

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.



338
339
340
341
# File 'lib/tina4/router.rb', line 338

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



332
333
334
335
# File 'lib/tina4/router.rb', line 332

def secure
  @auth_required = true
  self
end