Skip to content

Instantly share code, notes, and snippets.

View mloughran's full-sized avatar

Martyn Loughran mloughran

View GitHub Profile
@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 / 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 / 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 / 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 / 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!"
require 'rubygems'
require 'net/http'
require 'uri'
require 'json'
class GoogleClosure
class Error < RuntimeError; end
HOST = URI.parse('http://closure-compiler.appspot.com/compile')

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.

# Easily calculate mean and standard distribution of a distribution without
# collecting all values in memory
#
class Distribution
def initialize
@n, @sum_x, @sum_x_2 = 0, 0, 0
end
def <<(x)
@n += 1
# encoding: UTF-8
require 'digest/md5'
puts Digest::MD5.hexdigest("asdf") # => "912ec803b2ce49e4a541068d495ab570"
puts Digest::MD5.hexdigest("åß∂ƒ") # => "0d65ab8f1db3344230f46420e56e465f"
class Command
class << self
def run(command)
output = `#{command} 2>&1`.chomp
if $? != 0
raise " *** Command `#{command}` failed with the following output:\n#{output}"
end
output
end
end