class Phoenix::Channel

Defined in:

phoenix/channel.cr

Constant Summary

EVENTS = {close: "phx_close", error: "phx_error", join: "phx_join", reply: "phx_reply", leave: "phx_leave"}
LIFECYCLE_EVENTS = [EVENTS[:close], EVENTS[:error], EVENTS[:join], EVENTS[:reply], EVENTS[:leave]]

Instance Method Summary

Instance Method Detail

def join(timeout : UInt32 = @timeout) : Push #

Join the channel

Returns a Push instance for binding to reply events with Push#receive.

channel.join
  .receive "ok" do |response|
    puts "Joined successfully: #{response}"
  end
  .receive "error" do |response|
    puts "Unable to join: #{response}"
  end

[View source]
def leave(timeout = @timeout) : Push #

Leaves the channel

Unsubscribes from server events, and instructs channel to terminate on server.

channel.leave.receive "ok" do
  puts "Left successfully"
end

[View source]
def off(event : String, ref : UInt32? = nil) #

Unsubscibes to channel events


[View source]
def on(event : String, &block : JSON::Any, String?, String? -> ) : UInt32 #

Subscribes to channel events

Subscription returns a ref counter, which can be used later to unsubscribe the exact event listener.

ref_1 = channel.on "event" do
  # do stuff
end
ref_2 = channel.on "event" do
  # do other stuff
end
channel.off("event", ref_1)

Due to unsubscription, "do stuff" won't run, while "do other stuff" will still run on the "event".


[View source]
def on_close(&block : -> ) : UInt32 #

Hook into channel close


[View source]
def on_error(&block : JSON::Any, String?, String? -> ) : UInt32 #

Hook into channel errors


[View source]
def on_message(&on_message : String?, JSON::Any, String? -> JSON::Any) #

Overridable message hook

Receives all events for specialized message handling before dispatching to the channel callbacks. Must return the payload, modified or unmodified.

channel.on_message do |event, payload, ref|
  # handle payload here
  handled_payload
end

[View source]
def push(event : String, payload : JSON::Any = {} of String => JSON::Any, timeout : UInt32 = @timeout) : Push #

Send a message down the channel

channel.push("new_msg", JSON::Any.new({"text" => JSON::Any.new("Hello world!")}))

[View source]