With Celluloid, we can hide the async flow of a protocol using Signals.
The comparison is that in the Celluloid version, the #start
method now has the logic which describes the flow of the protocol.
-
-
Save halorgium/40663ee53468053b99ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# OLD | |
class Connection | |
def start(&block) | |
handshake | |
@result_callback = block | |
end | |
def handshake | |
send_data "handshake" | |
end | |
def on_handshake_completed | |
start_work | |
end | |
def start_work | |
send_data "start_work" | |
end | |
def on_work_done(result) | |
if result.ok? | |
@result_callback.call(result) | |
else | |
start_work | |
end | |
end | |
end | |
class Parser | |
def process_pkt(packet) | |
case packet.type | |
when 'handshake_complete' | |
@connection.on_handshake_complete | |
when 'work_done' | |
@connection.on_work_done(packet.payload) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# NEW | |
class Connection | |
include Celluloid | |
def start | |
handshake | |
loop do | |
result = start_work | |
return result if result.ok? | |
end | |
end | |
def handshake | |
send_data "handshake" | |
wait :handshake | |
end | |
def on_handshake_complete | |
signal :handshake | |
end | |
def start_work | |
send_data "start_work" | |
wait :work_done | |
end | |
def on_work_done(result) | |
signal :work_done, result | |
end | |
end | |
class Parser | |
def process_pkt(packet) | |
case packet | |
when 'handshake_complete' | |
@connection.on_handshake_complete | |
when 'work_done' | |
@connection.on_work_done(packet.payload) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment