Skip to content

Instantly share code, notes, and snippets.

@halorgium
Last active December 16, 2015 21:39
Show Gist options
  • Save halorgium/40663ee53468053b99ab to your computer and use it in GitHub Desktop.
Save halorgium/40663ee53468053b99ab to your computer and use it in GitHub Desktop.

Making async or network based protocols appear synchronous

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.

# 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
# 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