Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement on_close callback #4

Merged
merged 1 commit into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/s2/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ def close(message: nil)
@ws.close
end

def notify_closed(rm_id)
trigger_on_close(rm_id)
end

protected

def reply(message, status:)
Expand Down
9 changes: 9 additions & 0 deletions lib/s2/message_handler_callbacks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module MessageHandlerCallbacks
class_attribute :on_open_proc, default: nil
class_attribute :before_receive_proc, default: nil
class_attribute :after_send_proc, default: nil
class_attribute :on_close_proc, default: nil
end

class_methods do
Expand All @@ -20,6 +21,10 @@ def before_receive(&block)
def after_send(&block)
self.after_send_proc = block
end

def on_close(&block)
self.on_close_proc = block
end
end

protected
Expand All @@ -35,5 +40,9 @@ def trigger_before_receive(rm_id, message)
def trigger_after_send(rm_id, message)
instance_exec(rm_id, message, &self.class.after_send_proc) if self.class.after_send_proc
end

def trigger_on_close(rm_id)
instance_exec(rm_id, &self.class.on_close_proc) if self.class.on_close_proc
end
end
end
16 changes: 16 additions & 0 deletions spec/lib/s2/connection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -159,5 +159,21 @@
expect { connection.send_message(S2::Messages::Handshake, payload) }
.to change { connection.after_send_args }.from(nil).to(["123", message.to_json])
end

it "calls a callback on closing the connection" do
connection_class = Class.new(described_class) do
attr_reader :on_close_arg

on_close do |rm_id|
@on_close_arg = rm_id
end
end

connection = connection_class.new(ws, logger: Logger.new(nil))
connection.open("123")
connection.notify_closed("123")

expect(connection.on_close_arg).to eq("123")
end
end
end