SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.
follow me on Twitter

String.to_permalink

Posted on July 7th, 2007 by Alex Gorbatchev. In Ruby. No comments yet...

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

Posted on July 6th, 2007 by Alex Gorbatchev. In Ruby. No comments yet...

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

Posted on June 19th, 2007 by Alex Gorbatchev. In Ruby. No comments yet...

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

Posted on June 18th, 2007 by Alex Gorbatchev. In Rails, Ruby. No comments yet...

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?

Posted on June 9th, 2007 by Alex Gorbatchev. In Ruby. 1 comment so far...

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
home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr