Look up a gem's version history

Sometimes it might be helpful to have a version history for a gem, e.g. when you want to see if there is a newer Rails 2 version of your currently used gem.

At first you should search your gem at RubyGems. Example: will_paginate version history.

The "Tags" tab at GitHub might be helpful as well.

paul/progress_bar - GitHub

ProgressBar is a simple Ruby library for displaying progress of long-running tasks on the console. It is intended to be as simple to use as possible.

How to create Excel sheets with spreadsheet gem and use number formats for cells like money or date

The following snippet demonstrates how you could create excel files (with spreadsheet gem) and format columns so that they follow a specific number format like currencies or dates do.

require 'rubygems'
require 'spreadsheet'

Spreadsheet.client_encoding = 'UTF-8'

book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet :name => 'test'

money_format = Spreadsheet::Format.new :number_format => "#,##0.00 [$€-407]"
date_format = Spreadsheet::Format.new :num...

Using Solr with Sunspot

This describes all the steps you'll need to get Solr up and running for your project using the Sunspot gem.

Prepare Sunspot on your development machine

What you want in your Gemfile:

gem 'sunspot_rails'
gem 'sunspot_solr'
gem 'progress_bar' # for sunspot:solr:reindex

Now define what should be indexed within Solr from your ActiveRecord models, e.g.,

class Article << ActiveRecord::Base

  searchable do
    text :title
 ...

gammons/fake_arel - GitHub

Gem to get Rails 3's new ActiveRecord query interface (where, order) and the new scope syntax (chaining scope definitions) in Rails 2.

You also get #to_sql for scopes.

marcandre/backports - GitHub

Gem to get Ruby 1.9 features in Ruby 1.8.

colszowka/simplecov - GitHub

Code coverage for Ruby 1.9 with a powerful configuration library and automatic merging of coverage across test suites.

Note that rcov won't ever have support for Ruby 1.9, you're supposed to use rcov for 1.8 and simplecov for 1.9.

How to install a specific version of RubyGems (and how to downgrade)

Sometimes you want one distinct version of RubyGems to be installed to replicate the same behavior across multiple servers.

Usually would do this to update your RubyGems, but this always takes you to the latest version:

gem update --system

While there are ways around the interwebs that use the rubygems-update package and call its setup.rb, there is an undocumented switch you can use:

gem update --system 1.3.7

This updates to the given version, 1.3.7 in the above case, by walking the rubygems-update package way itself.

---...

Ruby Exception Class Hierarchy

This note summarizes the ruby exception hierarchy.

Exception
  NoMemoryError
  ScriptError
    LoadError
    NotImplementedError
    SyntaxError
  SignalException
    Interrupt
      Timeout::Error    # < ruby 1.9.2
  StandardError         # caught by rescue (default if no type was specified)
    ArgumentError
    IOError
      EOFError
    IndexError
    LocalJumpError
    NameError
      NoMethodError
    Ran...

Improved gitpt now part of geordi

Our gitpt script to generate git commits from Pivotal Tracker stories has been tweaked and polished and is now part of the geordi gem.

Install the freshly released version 0.7 now:

gem install geordi

This update will bring you commit with an initial "setup wizard" (that asks for your PT API key and initials) and prettier output: stories are colored by their state and thos...

Ruby < 2.4: Downcasing or upcasing umlauts

Using .downcase or .upcase on strings containing umlauts does not work as expected in Ruby versions before 2.4. It leaves the umlauts unchanged:

"Über".downcase
=> "Über"

"Ärger".downcase
=> "Ärger"

The very same applies for french accents (Thanks Guillaume!):

"Être ou ne pas être, telle est la question".downcase
=> "Être ou ne pas être, telle est la question"

Obviously, this leads to problems when comparing strings:

"Über".downcase == "über"
=> false

In Rails you can use ActiveSupports' [multib...

Don't compare datetimes with date ranges in MySQL and PostgreSQL

When selecting records in a date range, take care not to do it like this:

start_date = Date.parse('2007-05-01')
end_date = Date.parse('2007-05-31')
LogItem.where(:created_at => start_date .. end_date)

The problem is that created_at is a datetime (or Time in Ruby), while start_date and end_date are simple dates. In order to make sense of your query, your database will cast your dates to datetimes where the time component is 00:00:00. Because of this the query above will lose records created from `2007-05-31 00:00:0...

Detect mobile or touch devices on both server and client

Although it's tempting flirt with detecting mobile/touch devices with CSS media queries or Javascript feature detection alone, this approach will be painful when heavily customizing a feature beyond just tweaking the looks. Eventually you will want want the same detection logic to be available on both server and client side.

This card shows how to get a Ruby method touch_device? for your Rails views and a method TouchDevice.isPresent() for your Javascripts.

Note that we are detecting touch devices by grepping the user agent, and the ke...

Get color in the Capistrano output

Note: capistrano_colors was merged into Capistrano starting from v2.13.5. However, this requires Ruby 1.9+.

If you cannot upgrade Capistrano to 2.13.5+ (e.g. because you're still running on Ruby 1.8), simply put capistrano_colors into your Gemfile and require 'capistrano_colors' in your config/deploy.rb file.

tanoku/redcarpet - GitHub

Ruby bindings for Sundown, a fast and full-featured Markdown parser that lets you define renders for arbitrary output formats.

Writing Ruby Scripts That Respect Pipelines

Guide to writing CLI scripts in Ruby that play nice with pipe chains.

Managing Rails locale files with i18n-tasks

When internationalizing your Rails app, you'll be replacing strings like 'Please enter your name' with t('.name_prompt'). You will be adding keys to your config/locales/*.yml files over and over again. Not to miss any key and place each at the right place is a challenging task.

The gem i18n-tasks has you covered. See its README for a list of things it will do for you.

Note

The i18n-tasks gem does not understand aliases and will duplicate all referenced data when it writes locales. If yo...

How to fix: "500 Internal Server Error" after adding Rack::Bug

When Rack::Bug has been added to your project and your Apache2/Passenger only replies with an Error 500 (Internal Server Error) you won't get any love from both application and Apache logs.

You can start a script/server and try connecting there. It should also fail but you will most likely see this error:

Internal Server Error  
undefined method `new' for "Rack::Bug":String

While the following is (for some reason) working on OSX...

config.middleware.use "Rack::Bug", :secret_key => '...'

...you need to do this so it wor...

davetron5000/methadone - GitHub

Framework to write command-line apps in Ruby. Comes with a nice way of processing parameter options, some utility classes and Cucumber steps for testing your CLI app.

Pick a random element from an array in Ruby

[1,2,3,4].sample
# => e.g. 4

If you'd like to cheat and give different weights to each element in the array, you can use the attached initializer to say:

[1,2,3,4].weighted_sample([1,1,1,1000])
# => probably 4

ERB templates and comments

When you use one line Ruby comments in ERB templates you should never do this (notice the whitespace in front of #):

<% # my comment %>

<div>my html</div>

This leads to strange html output. To avoid long debugging sessions, you should never have a whitespace before the # character (but newline is allowed)

<%# this works as expected %>

<%
    # this works, too
    # foo bar baz
%>

Sequel: The Database Toolkit for Ruby

Seems like a useful gem for cases where ActiveRecord is overkill but you don't want to do everything by hand either.

Rails ERD – Entity-Relationship Diagrams for Rails

Gem to generate entity relationship diagrams from your Rails 3 ActiveRecord models. The diagram style is pretty and configurable.

ActsAsTaggableOn: Cache tag lists

For performance improvements (and to remove the need for eager loading), the ActsAsTaggableOn gem supports caching your tag lists directly in your model. To enable this, simply add a cached_tag_list column to your table.

Example:

class Company < ActiveRecord::Base
  acts_as_taggable_on :categories
end

The cache column has to be named cached_category_list.

Existing data

If you already have existing data, you have to save all records with tags once, after you've added the ...