Skip to content

Instantly share code, notes, and snippets.

@raws
Forked from anonymous/gist:658942
Created November 1, 2010 22:00
Show Gist options
  • Save raws/658949 to your computer and use it in GitHub Desktop.
Save raws/658949 to your computer and use it in GitHub Desktop.
module Intercept
class << self
attr_reader :interceptors
def intercept(command, method=nil, &block)
interceptor = { :command => command, :action => method || block }
(@interceptors ||= []) << interceptor
end
end
protected
def intercept(command)
self.class.interceptors.select do |interceptor|
interceptor[:command] == command
end.tap do |interceptors|
if block_given?
interceptors.each { |interceptor| yield interceptor }
else
interceptors
end
end
end
end
class BncsHandler
include Intercept
attr_reader :client, :packet, :unpacked
intercept 0x25, :ping
intercept 0x50, :check_revision
intercept(0x69) { log "HEY BABY" }
def initialize(client, packet, unpacked)
@client, @packet, @unpacked = client, packet, unpacked
end
def command
@command ||= unpacked[1]
end
def handle
log("S->C packet 0x%02X" % command)
log(packet.hexdump)
intercept(command) do |interceptor|
action = interceptor[:action]
case action
when Symbol then send(action)
when Proc then action.call(command)
end
end
end
protected
def log(text)
puts "[BNCS] #{text}"
end
def ping
log "ping!"
end
def check_revision
log "check_revision"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment