ruby snippets

Capistrano 2 task for backing up your MySQL production database before each deployment

Tagged ruby, rails, backup, mysql, capistrano  Languages ruby

This Capistrano task connects to your production database and dumps the contents to a file. The file is compressed and put in a directory specified with set :backup_dir, "#{deploy_to}/backups". This is a slight modification of All credit to court3nay.

task :backup, :roles => :db, :only => { :primary => true } do
  filename = "#{backup_dir}/#{application}.dump.#{}.sql.bz2"
  text = capture "cat #{deploy_to}/current/config/database.yml"
  yaml = YAML::load(text)

  on_rollback { run "rm #{filename}" }
  run "mysqldump -u #{yaml['production']['username']} -p #{yaml['production']['database']} | bzip2 -c > #{filename}" do |ch, stream, out|
    ch.send_data "#{yaml['production']['password']}\n" if out =~ /^Enter password:/

To automatically backup your data before you deploy a new version add this to config/deploy.rb:

task :before_deploy do

To restore the backup run the following command:

mysql database_name -uroot < filename.sql

Find the installation directory of a RubyGem package programmatically

Tagged gem, ruby, rubygems, path, package  Languages ruby

This snippet prints the full path to the Rails installation directory--the path is retrieved using the RubyGems API:

require 'rubygems'
# Specify version number
puts'rails', '=1.0.0').first.full_gem_path

Example output:


To find the directory where your gems are hiding, use:

gem env

There's also the gem which command:

$ gem which activesupport
(checking gem activesupport-2.3.2 for activesupport)

How to use Rails helpers from controllers, models, anywhere

Tagged url_for, helpers, ruby, rails, template, link_to  Languages ruby

How to use e.g. url_for where you need it, not where you’ve been told to use it:

Rails 4


Rails 3

class URLHelper
  include Singleton
  include ActionDispatch::Routing::UrlFor
  include Rails.application.routes.url_helpers

Rails 1-2.x

Use this snippet if you need to use one of the many Rails helpers in controllers or elsewhere:

class Helpers
    include Singleton
    include ActionView::Helpers::TextHelper
    include ActionView::Helpers::UrlHelper
    include ActionView::Helpers::DateHelper
    include ActionView::Helpers::TagHelper
    include ActionView::Helpers::ActiveRecordHelper


You can test named routes in the console through the app object:

app.get '/'
# Named route
app.image_path Image.first


For example, to obfuscate email use the mail_to helper and set the encoding to JavaScript:

Helpers.instance.mail_to "[email protected]", "My email", :encode => "javascript"

In Rails controllers there's no need to do anything, simply use the template instance to call helpers:

def index
   @template.link_to x, x.title


If you get this error:

Missing host to link to! Please provide :host parameter or set default_url_options[:host]

Fix it by specifying the host:

URLHelper.default_url_options[:host] = ''

Generate a TOC for a textile file

Tagged ruby, toc generation, textile, redcloth  Languages ruby

Takes a textile document as input (reads from a file) and generates a TOC (Table Of Contents) for it. The resulting output is a complete HTML document with the TOC and your document integrated. Requires Redcloth. Usage:

ruby ./textile_to_html_with_toc.rb my_textile_document.tex > my_textile_document.html

NOTE: Does not work with direct copy & paste because of a problem of correctly displaying the escaping quotes of the here document.

#!/usr/bin/env ruby
# author: marko dot haapala at aktagon dot com
# idea taken from here:
require "rubygems"
require "redcloth"

def generate_toc (file_name, headreg)
    document =
    toc = "" 
    document.gsub(headreg) do |match|
        number = $1
        name = $2
        header = name.gsub(/\s/,"+")
        toc << '#' * number.to_i + ' "' + name + '":#' + header + "\n"

def manipulate_body(file_name, headreg)
    document =
    document.gsub!(headreg) do |match|
        number = $1
        name = $2
        header = name.gsub(/\s/,"+")
        "\nh" + number + '. <a name="' + header + '">' + name + '</a>'

if ARGV[0] == nil 
    puts "Oh no! You didn't give me a filename :(" 
    exit 1

file_name = ARGV[0]
headreg = /^\s*h([1-6])\.\s+(.*)/
toc = generate_toc(file_name, headreg)
body = manipulate_body(file_name, headreg)
template = <<-'EOF'
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"\">
<html xml:lang=\"en\" lang=\"en\" xmlns=\"\">
        <META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">
        <link rel=stylesheet href=\"style.css\" type=\"text/css\">
puts eval("\"" + template + "\"")

Solution to "require': no such file to load -- readline (LoadError)" problem

Tagged readline, ruby, console, compile  Languages bash

If you've compiled Ruby from source, you might get this error when executing script/console:

/usr/local/lib/ruby/1.8/irb/completion.rb:10:in require': no such file to load -- readline (LoadError)

One way of fixing this is to compile readline, which is distributed along with the Ruby source:

cd /opt/src/ruby-1.8.5-p2/ext/readline
ruby extconf.rb
sudo make install

This works even after compiling Ruby, so no need to recompile... If you're wondering what readline is then this quote from the project homepage sums it up in one sentence: "The GNU Readline library provides a set of functions for use by applications that allow users to edit command lines as they are typed in."

Syntax highlighting code with Ruby and Ultraviolet

Tagged ultraviolet, ruby, themes  Languages ruby

This site uses Ultraviolet for syntax highlighting. Ultraviolet supports 50 languages and 20 themes, so it's sometimes difficult to pick the best theme, which is why I created the following code snippet that renders the code in all available themes and creates an HTML page displaying them all:

require 'uv'

language      = ARGV[1]
input_file    = ARGV[0]
line_numbers  = true
output_format = "xhtml"

input =

# Render input using all available themes
syntax_highlighted_code = ""
Uv.themes.each do |theme|
  syntax_highlighted_code << "<h2>#{theme}</h2>"
  syntax_highlighted_code << Uv.parse( input, output_format, language, line_numbers, theme)

# Template for output file
page_template = <<HTML_DOC
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""">

    #{{|theme| %Q(<link rel="stylesheet" type="text/css" href="css/#{theme}.css" />\n)}}
                <script type="text/javascript" src=""></script>
                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

# Write highlighted text to output"output.html", "w") do |file|
  file << page_template

Yes, using ERB templates would be better but interpolated strings work just fine... Save the code in highlight.rb and run it as follows:

highlight.rb ruby input_file.rb

Installing Ultraviolet and Oniguruma

Tagged onigurama, ultraviolet, ruby, ubuntu, install, oniguruma  Languages bash

First install Oniguruma

Oniguruma is a regular expression engine that Ultraviolet uses to parse text; Ruby also uses Oniguruma by the way. If you don't have Oniguruma on your system you'll get this error while installing Ultraviolet (at least on Ubuntu Linux):

oregexp.c:2:23: error: oniguruma.h: No such file or directory

This tells you that you should download and install Oniguruma. For me version 5.8.0 was the only version that worked, so execute this command to get the right version of Oniguruma:

$ wget

You now have the source package on your computer, so decompress it with the following command:

$ tar zxvf onig-5.8.0.tar.gz

If everything went fine, change current directory:

$ cd onig-5.8.0/

Next, run configure:

$ ./configure

Watch the output closely and fix any errors reported, then run make:

$ make

To build and install Onigurama run:

$ sudo make install

I managed to get the following errors from Ultraviolet with other versions of Oniguruma, but these went away after installing 5.8.0 and re-installing Oniguruma:

Parsing error in // ==UserScript==: wrong number of arguments (2 for 0) #<Textpow::SyntaxNode:0xb7c91780>

Installing Ultraviolet and dependencies

Next install Ultraviolet with RubyGems:

$ sudo gem install -r ultraviolet --include-dependencies

Select which gem to install for your platform (i486-linux)
 1. oniguruma 1.1.0 (mswin32)
 2. oniguruma 1.1.0 (ruby)
 3. Skip this gem
 4. Cancel installation
> 2
Building native extensions.  This could take a while...
Successfully installed ultraviolet-0.10.0
Successfully installed textpow-0.9.0
Successfully installed oniguruma-1.1.0
Successfully installed plist-3.0.0

Test that Ultraviolet works by running the following code with irb:

$ irb

require 'rubygems'
require 'uv'
puts Uv.syntaxes.join( "\n" )
puts Uv.themes.join( "\n" )
input = <<HTML

puts Uv.parse( input, "xhtml", "html", true, "slush_poppies")


You might get this error:

require 'uv'
LoadError: cannot open shared object file: No such file or directory - /usr/lib/ruby/gems/1.8/gems/oniguruma-1.1.0/lib/

This message is a bit confusing. It means Ruby can't find, not as you could believe.

To fix this, check if the library has been linked:

$ ldconfig -p|grep libonig

If the library is not linked, add the path to the directory where the file is located to /etc/


include /etc/*.conf

Then run:

$ ldconfig

Another way of fixing this problem would be to tell the build script to install it to /usr/lib.

How to install the exception_logger Rails plugin and protect the logs with basic authentication

Tagged ruby, exception_logger, install, routes, rails, basic, authentication  Languages ruby

This snippet explains how to install and use the Rails exception_logger plugin. I'll also show you how to protect your logs by extending the plugin with basic authentication.

script/plugin source
script/plugin install exception_logger

I'm using Rails Edge on this project, so I had to install classic pagination also:

script/plugin install svn://

Next create and execute the migration file:

./script/generate exception_migration
rake db:migrate

Before starting the server we need to setup the routes:

map.exceptions '/logged_exceptions/:action/:id', :controller => 'logged_exceptions', :action => 'index', :id => nil

You also need to include the ExceptionLoggable in your ApplicationController:

class ApplicationController < ActionController::Base
  include ExceptionLoggable

Start your server and access the exception log at /logged_exceptions.

Exceptions can contain email addresses, passwords, credit card numbers, so you'll want to protect /logged_exceptions from the public. This can be done by adding the following code to the end of environment.rb:

config.after_initialize do
  require 'application' unless Object.const_defined?(:ApplicationController)
  LoggedExceptionsController.class_eval do
    before_filter :authenticate


    def authenticate
      authenticate_or_request_with_http_basic do |username, password|
        username == "foo" && password == "bar"

With this code we add a before filter that shows a login dialog to anyone trying to access /logged_exception/. Note that this requires Rails 2.0 basic authentication to work, so make sure you have the proper version installed.

How to benchmark your Ruby code

Tagged benchmark, performance, ruby  Languages ruby

You can easily benchmark your Ruby code like this:

require 'benchmark'
seconds = Benchmark.realtime do
    sleep 1
print "#{seconds} elapsed..."

The output should be close to 1 second.