Skip to content

Instantly share code, notes, and snippets.

View mloughran's full-sized avatar

Martyn Loughran mloughran

View GitHub Profile

Getting started

First add your twitter username and password. Then server.rb and once it's started open websocket.html in your browser. You should see some tweets appear. If not take a look at the javascript console.

require 'rubygems'
require 'net/http'
require 'uri'
require 'json'
class GoogleClosure
class Error < RuntimeError; end
HOST = URI.parse('http://closure-compiler.appspot.com/compile')
@mloughran
mloughran / gist:720094
Created November 29, 2010 15:45
Example of subclassing WebSocket::Connection
require 'rubygems'
require 'eventmachine'
require 'em-websocket'
class CustomWSConnection < EventMachine::WebSocket::Connection
def trigger_on_message(msg)
send "Pong: #{msg}"
end
def trigger_on_open
send "Hello Client!"
@mloughran
mloughran / gist:721430
Created November 30, 2010 09:52
Appending to a string vs stringIO
require 'rubygems'
require 'benchmark'
require 'stringio'
Benchmark.bm do |x|
n = 1000000
x.report('string') do
string = ''
appended = 'b' * 100
@mloughran
mloughran / unmasking_benchmark.rb
Created April 4, 2011 18:56
Making WebSocket unmasking fast in ruby
module EventMachine
module WebSocket
class MaskedString < String
def read_mask
raise "Too short" if bytesize < 4 # TODO - change
@masking_key = String.new(self[0..3])
end
def slice_mask
slice!(0, 4)
@mloughran
mloughran / watch.rb
Created September 14, 2011 14:27
em-hiredis watch-multi-exec example
require 'em-hiredis'
EM.run {
redis = EM::Hiredis.connect
redis.set('foo', 'value')
redis.watch('foo') {
puts "Watching - try changing key foo within 1s"
EM.add_timer(1) {
@mloughran
mloughran / pubsub_example.rb
Created September 14, 2011 15:05
em-hiredis pubsub example
require 'em-hiredis'
EM.run {
require 'em-hiredis'
redis = EM::Hiredis.connect
# If you pass a block to subscribe it will be called whenever a message
# is received on this channel
redis.pubsub.subscribe('foo') { |msg|
p [:received_foo, msg]
@mloughran
mloughran / Gemfile
Last active September 27, 2015 17:48
Firefox orphaned WebSocket connection testcase
source :rubygems
gem 'em-websocket'
gem 'sinatra'
@mloughran
mloughran / fiber_cache.rb
Created November 4, 2011 19:36
Proof of concept Redis cache, which blocks fiber if required on access
require 'eventmachine'
require 'em-hiredis'
require 'fiber'
class Cache
include EM::Deferrable
def initialize(key)
$redis.get(key) { |v|
@value = v
@mloughran
mloughran / gist:1382605
Created November 21, 2011 13:21
Potential async transaction api for em-hiredis
require 'em-hiredis'
class EM::Hiredis::Client
class Transaction
include EM::Deferrable
def initialize(redis)
@redis = redis
end