Skip to content

Instantly share code, notes, and snippets.

View norman's full-sized avatar
🪕
Scruggs not drugs

Norman Clarke norman

🪕
Scruggs not drugs
View GitHub Profile
class Author < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :author
end
@author = Author.find(params[:id], :include => :books)
class Sound < Test::Unit::TestCase
include Spanish::Phonology
test "should get sound from symbol" do
sound = Sound.new("b")
assert_equal "b", sound.symbol
assert sound.labial?
assert sound.stop?
assert sound.consonantal?
# ruby-1.9.1-p243
"é".center(5, 'a') # => "aaéaa"
"é".center(5, "á") # => "ááéáá"
# ruby-1.9.1-p378
"é".center(5, 'a') # => "aaéaa"
"é".center(5, 'á') # => "áéá"

Various snippets that were annoying to create and that I don't want to forget

vim regexp to convert CSS to SASS:

g/^(\s*)([a-z-]):\s*(.*);/s//\1:\2 \3/g

# Here's a piece of functionality I need to access often inside my library. It breaks an int
# into an array of bits, with each bit's position in the int corresponding to its array
# index. This gives me a consise way to check to see if lots of different bits are set.
123.to_s(2).reverse.split("").map(&:to_i)
# So, where do I put this? Should I monkey-patch Fixnum?
class Fixnum
def to_bit_array
to_s(2).reverse.split("").map(&:to_i)
end
module MyNamespace
class << self
# I want this utility method available everywhere inside my namespace,
# but I don't want to expose it in the API, so let's make it "protected."
def do_something
puts "hello"
end
protected :do_something
end
$ lua -e 'for i=1,4 do print(string.byte("ザ", i)) end'
227
130
182
$ lua -e 'print(string.char(227, 130, 182))'
# It's pretty easy to set a custom method as the basis of your friendly_id if
# you want to incorporate information from another model in the friendly_id.
class City < ActiveRecord::Base
belongs_to :state
has_friendly_id :city_and_state, :use_slugs => true
# This will return something like "San Francisco, California". It can be used
# as a display name in your views, and also as the basis of the friendly_id
# because it will be processed by the plugin to remove spaces, punctuation,
Selecting 10 rows from a table with 100,000 records:
MYSQL | SQLITE3 | POSTGRES |
--------------------------------------------------------
Ordered SELECT id 0.021 | 0.040 | 0.021 |
Ordered SELECT * 0.001 | 0.001 | 0.006 |
Random SELECT id 0.070 | 0.132 | 0.040 |
Random SELECT * 0.607 | 0.176 | 0.061 |
# $ mysql --version
# mysql Ver 14.14 Distrib 5.1.43, for apple-darwin10.2.0 (i386) using EditLine wrapper
# $ psql --version
# psql (PostgreSQL) 8.4.2
# contains support for command-line editing
# $ sqlite3 --version
# 3.6.12
# $ ruby --version
# ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-darwin10.2.0]
# $ uname -a