Skip to content

Instantly share code, notes, and snippets.

View raggi's full-sized avatar

James Tucker raggi

View GitHub Profile
@raggi
raggi / tsc.rb
Created May 14, 2012 23:12
Thread safe counter
class ThreadsafeCounter
include Comparable
def initialize(initial = 0)
@mutex = Mutex.new
@count = initial + 0
end
def incr
@mutex.synchronize { @count += 1 }
@raggi
raggi / encode_io.rb
Created May 9, 2012 19:35
csv generation, conversion, with utf16le - example
require 'iconv' unless "".respond_to?(:encode)
require 'active_support/basic_object'
# = EncodeIo
#
# This is essentially a basic delegation class. The reason it isn't
# using the delegate library from stdlib is that FasterCSV has special
# casing for io classes. In order to keep using this, we need #kind_of?
# and #class to pretend that this is the original class.
#
@raggi
raggi / mysql2_column_cache.rb
Created March 16, 2012 00:48
Mysql2 Column Cache for Rails 3.0.12
# = MONKEY PATCH: Memoize Mysql2 Columns
#
# Reduces SHOW FIELDS selects in production to essentially 0 calls.
#
# == Reason:
#
# * We have some pages that are (with rails 3.0.12) generating nearly 1200 SHOW
# FIELDS sql statements.
# * These come from ActiveRecord::Associations during complex join semantics.
# * Esentially, through some relations, Arel::Table instances don't have
# CAVEATS: only known to support 1.8.15 and master as of 2012/2/1
if Gem::Specification.respond_to?(:find_by_name)
if Gem.respond_to?(:unresolved_deps)
def unresolved
Gem.unresolved_deps
end
elsif Gem::Specification.respond_to?(:unresolved_deps)
def unresolved
Gem::Specification.unresolved_deps
@raggi
raggi / rfc3986.rb
Created December 23, 2011 19:51
RFC3986.rb
class Uri
module Escaping
RESERVED = []
%<:/?#[]@!$&'()*+,;=>.each_byte { |b| RESERVED << b }
ESCAPE_MAP = Hash.new do |h,k|
h[k] = RESERVED.include?(k) ? '%%%02X' % k : k.chr
end
0.upto(255) { |i| RESERVED[i] }
def ObjectSpace.preload
starting_size = $".size
ObjectSpace.each_object do |o|
o.respond_to?(:constants) && constants.each { |c| o.const_get(c) }
end
retry unless $".size == starting_size
end
class A
def initialize klass
klass.class_eval do
def a; end
end
end
new self
allocate.a
end
@raggi
raggi / pager_duty_api.rb
Created November 23, 2011 19:07
An API class for PagerDuty
require 'rubygems'
require 'mechanize'
require 'rack/utils'
require 'net/http/persistent'
require 'yajl'
class PagerDutyApi
class ApiError < StandardError
attr_reader :request, :response
def initialize request, response
require 'sinatra'
require 'eventmachine'
get '/' do
stream(:keep_open) do |out|
count = 0
timer = EM.add_periodic_timer(1) do
out << "<p>ohai</p>\n"
count += 1
if count == 10
@raggi
raggi / wtf.irb.rb
Created October 26, 2011 16:53
wtfbbq ruby?
>> begin; raise 'boom'; rescue; end
=> nil
>> begin; raise 'boom'; rescue => e; end
=> #<RuntimeError: boom>