Skip to content

Instantly share code, notes, and snippets.

View mloughran's full-sized avatar

Martyn Loughran mloughran

View GitHub Profile
@mloughran
mloughran / gist:2837064
Created May 30, 2012 15:39
Two state deferrable synchronisation primitive, in need of a name
require 'eventmachine'
# Allows calling set/clear at will, and ensures that only a single on_set or
# on_clear deferrable is running concurrently. It also ensures that
# un-necessary callbacks are not run, i.e. set-unset-set in sequency only
# requires the on_set callback to run once
#
# The blocks/procs supplied for on_set and on_clear must return deferrables
#
class Thing
@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
@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 / Gemfile
Last active September 27, 2015 17:48
Firefox orphaned WebSocket connection testcase
source :rubygems
gem 'em-websocket'
gem 'sinatra'
@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 / 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')
# 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
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