Color Output with Test:Unit, AutoTest and Ruby 1.9

If you are testing using Test:Unit (rather than RSpec) and you’re using Ruby 1.9.* colorized output of your tests using Autotest will not be immediately available. Since, 1.9 comes with mini test the test/unit/ui/console/testrunner.rb script is not loaded and not available and will break your tests.

The solution is to require Test:Unit version 2.0.0 in your Gemfile, require the testrunner.rb script in test/test_helper.rb and reopen and implement the guess_color_availability method.

Then you can just run the autotest command (or bundle exec autotest) from your project directory. When you save a file your tests will be run for the file that has been changed and the results will be fully colorized!

Aliasing Attributes in Ruby on Rails

Alias an attribute with alias_attribute method.

The first argument is the name for the new attribute, while the second argument is to identify the attribute that is already defined.

class User < ActiveRecord::Base
  alias_attribute :username, :login
end

Rails 3 Config Auto Load Paths in Application.rb

In Rails 3 files in lib/ are no longer loaded by default. It’s a snap to auto load these classes by adding the following line to config/application.rb

    config.autoload_paths += %W(#{config.root}/lib)

This is commented out around line 16. Either replace it or uncomment it out to reflect the location where your lib classes are located.

Rails Send_File in Production Delivers an Empty File

If you’re running Rails in production it will by default be configured to let apache or nginx send files for you. If you’re handling file downloads yourself with send_file

send_file("path/to/file.txt")

you will notice that the downloaded files are empty. To get around this just comment out the following in your config/environments/production.rb file.

  # comment out for production because apache/nginx are not doing this for us
  #config.action_dispatch.x_sendfile_header = "X-Sendfile"

Rails Find All by Birthday: How to Find Upcoming Birthdays with ActiveRecord

There are a few ways to solve this problem. However, I think the easiest is to cache the day of the year that the user is born on as an integer. If stored alongside the timestamp we can quickly get a list but properly handle the full birthday elsewhere, such as in the view. You don’t want to rely on just the cached day of year because leap year is not accounted for.

The model will need both born_at and birthday columns.

create_table :users do |t|
  t.timestamp :born_at  # full timestamp
  t.integer :birthday 	# just the day of year
end

The user model also needs a callback (before_save) to set and or update the cached birthday column based on the full timestamp. For convenience, a named scope can be added to the model which will let you call User.birthdays.

class User
  # User.birthdays
  scope :birthdays, lambda { where('birthday in(?)', 7.times.map{|i| Time.now.yday + i}) }

  def before_save
  	self.birthday = born_at.yday
  end
end

You could also use the week in year (1 – 52) for the cache. Using the day you can look an arbitrary number of days ahead.

Simple String Concatenation of a Collection Written as a Helper for Rails

At Railsconf last week I took Greg Pollack’s online course Rails Best Practices. The interface is gorgeous and the instructions are excellent. One of the lessons involved taking a partial and moving it into a helper. I was reminded how difficult such a simple task can be. I have written about this before Yield a Block Within Rails Helper Method with Multiple Content Tags. However, that post aims to solve a slightly different problem, where the helper method takes the captured text from a block passed as an argument which essentially acts as a wrapper.

The difficulty isn’t with the logic itself and or the complexity/verbosity that the code is likely to produce. Rather, it is difficult because you have to endlessly concatenate strings and this something somewhat uncommon when programming with ruby. We have to remember that we’re working with a buffer of text about to be flushed. Here is a simple code snippet that shows how to write a helper method that loops over a collection of objects.

  def bookmarks_for(user=nil)
    content_tag(:div, :id => "bookmarks") do
      user.bookmarks.each do |bookmark|
        concat(
          content_tag(:strong) { bookmark.member_name } +
          excerpt(bookmark.body, '', 100)
        )
      end.join
    end
  end

Notice the use of the concat() method the “+” sugb and .join() method. All three of which bring these statements together into one final piece of html called in the view.

<%= bookmarks_for(@user) %>

Reusing Scopes (Formerly Named_scope) In Rails 3

You can easily chain scopes together in your models.

class Article < ActiveRecord::Base
scope :ordered, order('position ASC')
scope :published, ordered.where('published = ?', true)
scope :for_homepage, published.limit(3)
end


Article.for_homepage.to_sql
# => SELECT \"articles\".* FROM \"articles\" WHERE (published = 't') ORDER BY position LIMIT 3

Installing Ruby on Rails 3, MySQL, Git, Ruby Enterprise Edition, Passenger (Mod_Rails) on Ubuntu with Rackspace Cloud.

Short and sweet. Here all the commands I run in this order to set up a brand new box. It usually takes about 10 – 15 minutes on a 256 MB RAM instance. Compiling Ruby Enterprise Edition, which is super easy, will take the most amount of time. It will seem to have gotten stuck. It hasn’t. It just takes a little while.

# Update, upgrade and install all necessary packages for Ruby on Rails server if you've got a fresh Ubuntu slice
apt-get update
apt-get upgrade

apt-get install build-essential patch libssl-dev libreadline5-dev

apt-get install ruby1.8-dev ruby1.8 ri1.8 rdoc1.8 irb1.8 libreadline-ruby1.8 libruby1.8 libopenssl-ruby imagemagick librmagick-ruby1.8 librmagick-ruby-doc libfreetype6-dev xml-core postfix
# postfix will prompt you for details
# use Internet Site and enter in the domain name you are planning on sending email from 

apt-get install apache2 apache2-prefork-dev libapr1-dev libaprutil1-dev libcurl4-openssl-dev git-core mysql-server mysql-client libmysqlclient15-dev libmysql-ruby
# mysql will also prompt you to set up a root user account. set the password to be anything you like

# next, download the latest release of ruby enterprise edition but when you're installing it on your own machine version numbers and release dates may have changed.
# pay attention to the version and release date before the file extension. it will be something like
# ... 1.8.7-2010.02
# this will change to something like 2011.03, 2011.04... etc in the future.
# just double check the paths on when you are installing and make the necessary substitutions

# ruby enterprise edition is available at http://www.rubyenterpriseedition.com/download.html
wget http://rubyforge.org/frs/download.php/71096/ruby-enterprise-1.8.7-2010.02.tar.gz
tar xzvf ruby-enterprise-1.8.7-2010.02.tar.gz 

./ruby-enterprise-1.8.7-2010.02/installer
# this may take a little while (just follow the instructions)
# and hit enter to install in default location (recommended) when prompted 

# and to install passenger (which is mod_rails for apache)
/opt/ruby-enterprise-1.8.7-2010.02/bin/passenger-install-apache2-module 

# i take the output from the above script and add it to my available modules directory
vim /etc/apache2/mods-available/passenger.conf

# and enter something like this in the newly created file (your version numbers will prob. be different)
LoadModule passenger_module /opt/ruby-enterprise-1.8.7-2010.02/lib/ruby/gems/1.8/gems/passenger-3.0.2/ext/apache2/mod_passenger.so
PassengerRoot /opt/ruby-enterprise-1.8.7-2010.02/lib/ruby/gems/1.8/gems/passenger-3.0.2
PassengerRuby /opt/ruby-enterprise-1.8.7-2010.02/bin/ruby

# and then sym link it to the enabled directory so that apache knows about it
ln -s /etc/apache2/mods-available/passenger.conf /etc/apache2/mods-enabled/passenger.conf

# and now i want to include ruby enterprise edition in my path so i add it to my profile (again make sure the path is correct)
vim /etc/profile.d/passenger.sh
export PATH=/opt/ruby-enterprise-1.8.7-2010.02/bin:$PATH

. /etc/profile.d/passenger.sh
# the "." file will make the setting available for the current terminal session
rails -v
ruby -v
rake -v
# should all be working now
# and
which ruby
# should point to the ruby enterprise edition under /opt

# next i
# set up public/private keys
# so i can do
# ssh localhost without using a password
cd
test -e ~/.ssh/id_dsa.pub || ssh-keygen -t dsa
cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys2

# and finally install git
apt-get install git-core

You should now have a server ready to server ruby on rails applications!

Rails 3 disable_with Does Not Work with Ajax Remote Form_for

It appears that the :disable_with option on the submit_tag form helper method does not behave as expected with remote forms. I’m not sure if this is a bug or not. But the fix is pretty straight forward, but perhaps a little difficult to trouble shoot. Using submit_tag inside a remote form

&lt;%= submit_tag "Submit", :disable_with =&gt; "Submitting...." %&gt;

Will not work.

You have to edit your public/javascripts/rails.js file around line #167

and change

document.on("ajax:after", "form", function(event, element) {

to

document.on("ajax:complete", "form", function(event, element) {

Then things will behave as expected. This assumes you are using Prototype (rather than jQuery).