Skip to content

Instantly share code, notes, and snippets.

@hawx
hawx / Rakefile
Created July 4, 2010 15:41
Minify a folder of js with `rake minify`
desc "minify js and put into one file"
task :minify do
require 'jsmin'
out = 'min.js'
glb = '*.js'
res = ''
Dir[glb].each do |path|
res << File.read(path) << "\n"
# Gets the genres for tracks in a playlist called 'Genres'in iTunes
# and sets them using data from wikipedia.
#
# Uses the album name for the search, but won't try anything fancy
# if it can't find the labum it will just ignore it.
#
# ref: http://www.apeth.com/rbappscript/05propel.html
require 'appscript'
require 'nokogiri'
@hawx
hawx / scoped-monkey-patch.rb
Created July 26, 2010 16:16
This is how I would maybe work around the problem of scoping monkey patches. Which should be coming in Ruby 2.0
module Test
class String < ::String; end
p String.new("Test::String").class
#=> Test::String
p ::String.new("::String").class
#=> String
p "::String".class
#=> String -> Would be better as Test::String
end
# Matches an Array (of trues and falses) to a given Array. Fills itself
# with preference to fill where true first, then any spare items are put
# in place of false, then nils are used for remaining falses.
#
# input = ["a", "b", "c"]
# match = [true, false, false, true]
#
# match.optimise_fill(input)
# #=> ["a", "b", nil, "c"]
#
@hawx
hawx / colours.rb
Created December 16, 2010 17:24
Add colour to your output.
# Usage:
#
# puts green("I'm green")
# puts red("I'm red")
# puts bold("I'm bold")
#
def colour(text, code)
"#{code}#{text}\e[0m"
end
@hawx
hawx / a_bench.rb
Created February 10, 2011 17:19
Setting local variables within procs object, with benchmarks
require_relative 'local_in_procs'
f = lambda { message }
a = {:message => "Hello, world!"}
# Test the speed when using normal proc params
f_control = lambda {|a| a[:message] }
def rand_letters(n, l)
r = []
@hawx
hawx / rspec_all_of.rb
Created March 30, 2011 15:55
All_of matcher for rspec
# Not the best example, but
#
# it "is an array of Hashes" do
# all_of(subject).should be_kind_of Hash
# end
#
class AllOf
def initialize(items)
@items = items
@hawx
hawx / p_debug.rb
Created July 21, 2011 14:46
Find those debug statements
module Kernel
def p(*arg)
raise StandardError
rescue => e
$stdout.puts "p: #{e.backtrace[1]}"
end
def puts(*arg)
raise StandardError
rescue => e

Key-Value Store

Simplest key-value store that is usable (I think). Uses the stdlib [PStore][ps] for storage which is not suited to storing large pieces of data, but isn't that the point of a key-value store?

GET / returns a json encoded array of keys (each as strings).

POST /

@hawx
hawx / destructure.rb
Created September 16, 2011 17:37
Allow methods to use hashes or not as arguments
class Array
def destructure(*arr)
if size == 1 && first.is_a?(Hash)
arr.map {|k| first[k] }
else
self
end
end