String.to_permalink
Converts a string to a URL style permalink.
class String
def to_permalink
s = self
s = Iconv.iconv('ascii//ignore//translit', 'utf-8', s).to_s
s.gsub!(/^\W+|\W+$/, '')
s.gsub!(/\W+/, '-')
s.strip!
s.downcase!
s.squeeze!(' ')
s.gsub(/\ +/, '-')
end
end
Unindenting text block
Unindenting a block of text involves finding a common minimum indent in every line and removing it. Here’s how I have done it. As with any text processing, the larger the text is, the slower it is.
def unindent_text(src)
indents = []
src.each_line do |line|
indents < < $1.length if not line =~ /^\s*$/ and line =~ /^(\s+)/
end
indent = indents.min
return src if indent == 0
lines = []
src.each_line do |line|
lines << line.gsub(/^\s{#{indent}}/, '').gsub(/(\r\n|\n|\r)$/, '')
end
lines.join("\n")
end
in `latest_partials’: undefined method `[]‘ for nil:NilClass
If you are suddenly getting in `latest_partials': undefined method `[]' for nil:NilClass error when calling some gem methods like Gem.latest_load_paths or Gem.path, check your gems folder (on a PC it’s /Ruby/lib/ruby/gems/1.8/gems). Make sure there are no foreign folders or files in there. Rubygems expects all folders to be in <name>-<version> format.
find_by_sql() custom columnts trick
Just stumbled on the fact that ActiveRecord automatically creates properties for all column in a SQL query, not just those in the table.
Model.find_by_sql("SELECT *, COUNT(*) AS rank FROM ...").each do |item|
puts "%s (%d)" % [item.name, item.rank]
end
Where’s Math.min and Math.max in Ruby?
Maybe it’s just me and I don’t know where to look, but this isn’t something I’m interested in spending 30 minutes looking for.
module Math
def self.max(a, b)
a > b ? a : b
end
def self.min(a, b)
a < b ? a : b
end
end