Skip to content

Kemal Example

Jeremy Woertink edited this page Jan 8, 2025 · 1 revision

Here's a rough example on using with Kemal

require "uuid"
require "kemal"
require "cable"
require "cable-redis"

Cable.configure do |settings|
  settings.route = "/cable"    # the URL your JS Client will connect
  settings.token = "token"     # The query string parameter used to get the token
  settings.url = ENV.fetch("CABLE_BACKEND_URL", "redis://localhost:6379")
  settings.backend_class = Cable::RedisBackend
  settings.backend_ping_interval = 15.seconds
  settings.restart_error_allowance = 20
  settings.on_error = ->(error : Exception, message : String) do
    # send to error reporting
  end
end

module ApplicationCable
  class Connection < Cable::Connection
    # whatever you want your identifier to be
    identified_by :identifier

    def connect
      self.identifier = UUID.random
    end
  end
end

class CableHandler(T) < Kemal::Handler
  @cable : Cable::Handler(T)
  def initialize
    Cable::Handler(T).new
  end
  def call(context)
    # There's probably a better way to do this...
    @cable.call(context)
    call_next context
  end
end

add_handler CableHandler(ApplicationCable::Connection).new

class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params["room"]}"
  end
end

get "/" do
  "Hello World!"
end

Kemal.run

From here you'd just handle the javascript side as normal.

Clone this wiki locally