Skip to content

Instantly share code, notes, and snippets.

View PatrickTulskie's full-sized avatar

patrick tulskie PatrickTulskie

View GitHub Profile
@PatrickTulskie
PatrickTulskie / double_vs_single_bench.rb
Created May 26, 2011 15:07
Double Quotes vs Single Quotes... FIGHT!
require 'rubygems'
require 'benchmark'
GC.disable
Benchmark.bm do |x|
x.report('Double Quotes') { 10000000.times { "[WARNING] This is really stupid." } }
x.report('Single Quotes') { 10000000.times { '[WARNING] This is really stupid.' } }
end
require 'benchmark'
class A
def test
100.times do
yield
end
end
end
@PatrickTulskie
PatrickTulskie / arrayify.rb
Created April 29, 2011 18:39
Normalize Single Object vs Arrays
# I hate this pattern, but it's something I have to deal with when parsing XML using HTTParty all the time.
class Object
def arrayify
self.is_a?(Array) ? self : [self]
end
end
hsh = { :name => 'Hashy Mustache' }
arry = [{ :name => 'Mason Arrayson' }]
@PatrickTulskie
PatrickTulskie / array_grep_vs_select.rb
Created February 18, 2011 16:53
Benchmark comparing ruby array grep vs select with a match
require 'rubygems'
require 'benchmark'
test_array = %w(hamburger cheeseburger goatburger veggieburger lettuce tomato ketchup superburger)
Benchmark.bm do |x|
x.report { 1000000.times { test_array.grep(/burger/) } }
x.report { 1000000.times { test_array.select { |item| item.match(/burger/) } } }
end
@PatrickTulskie
PatrickTulskie / parse_benchmark.rb
Created January 17, 2011 05:08
Time.parse vs DateTime.parse performance testing
require 'rubygems'
require 'date'
require 'active_support'
require 'benchmark'
test_time = "2011-01-16 22:48:03 EST"
Benchmark.bm do |x|
x.report { 100000.times { Time.parse(test_time) } }
x.report { 100000.times { DateTime.parse(test_time) } }
module RedisLock
def lock_for_update(key, timeout = 60, max_attempts = 100)
if self.lock(key, timeout, max_attempts)
response = yield if block_given?
self.unlock(key)
return response
end
end
@PatrickTulskie
PatrickTulskie / burgerize_keys.rb
Created December 2, 2010 17:08
Method for quickly converting hashes of ingredients to proper burgers.
class Hash
def burgerize_keys!
self.keys.each { |key| self["#{key}_burger"] = self.delete(key) }
return self
end
end
class HashMapEnterpriseEdition < Hash
def burgerize_keys!
require 'rubygems'
require 'httparty'
class NFLStream
attr_accessor :current_scores
include HTTParty
format :json
base_uri "http://www.nfl.com"
@PatrickTulskie
PatrickTulskie / tracking_puts.rb
Created November 19, 2010 06:22
Find out where in your application puts is happening
def puts(s)
file = File.basename(caller.first)
super("puts() from #{file}: #{s}")
end
def print(s)
file = File.basename(caller.first)
super("print() from #{file}: #{s}")
end
class Array
def map_with_index(&block)
counter = 0
self.inject([]) { |mapped, item| mapped << block.call(item, counter); counter += 1; mapped }
end
end