Last active
December 25, 2015 19:48
-
-
Save lukewendling/7030008 to your computer and use it in GitHub Desktop.
Ruby meta - instance_eval inside a block
This file contains hidden or 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
# Demonstrates a basic module mixin and a slightly advanced meta technique: | |
# the use_socket (line 13) wrapper method connects to a server and issues | |
# various SocketIO commands. I use instance_eval (line 16) with a recipient | |
# SocketIO object, not an instance of the caller (NodeMessenger). | |
# instance_eval runs the passed block with receiver of self, which is a | |
# SocketIO object. | |
# The general purpose of this code is to talk to a Socket.io server | |
require 'SocketIO' | |
module NodeSocket | |
class NodeCantConnect < StandardError; end | |
def use_socket(&block) | |
SocketIO.connect(@chat.location) do | |
after_start do | |
instance_eval &block | |
disconnect | |
end | |
end | |
rescue Errno::ECONNREFUSED | |
raise NodeCantConnect | |
end | |
private :use_socket | |
end | |
# node_messenger | |
require 'node_socket' | |
# def: send messages and events to chat sessions | |
class NodeMessenger | |
include NodeSocket | |
def initialize(chat) | |
@chat = chat | |
end | |
# expects hash with keys :name and :data | |
# users will see this | |
def chat(msg) | |
use_socket do | |
send_event 'systemMessages', msg | |
end | |
end | |
def startup | |
use_socket do | |
send_event 'startup', nil | |
end | |
end | |
def shutdown | |
use_socket do | |
send_event 'shutdown', nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment