Monday, March 15, 2010

Rails 3: Code coverage with rcov

UPDATE: Added support for ruby 1.9 and rails 3.1

I use rcov to make sure I have 100% test coverage on my rails projects. In earlier versions of rails I used the rails_rcov plugin to accomplish this task. Since rails 3 allows rake tasks to be imported by gems, I decided to write a gem with a rake task that reports on code coverage.

rails_code_qa
Currently rails_code_qa runs the unit, functional, and integration tests for a Rails 3 app. It generates 2 different coverage reports. Unit test coverage is calculated on models, helpers, and lib; functional test coverage is calculated on the controllers. Coverage is not calculated on integration tests. In my experience I have found this to be a good way to calculate coverage because it encourages you to write unit tests that cover your core code very well. 

Install
All you need to do to install rails_code_qa in your rails 3 app is add the following line to your Gemfile.
gem "rails_code_qa"
Then update the bundle for the rails app with the following command.
bundle install
Bundler automatically pulls from rubygems.org and installs any dependencies (rcov) that rails_code_qa needs.

Usage
rails_code_qa adds a few useful rake tasks to your rails app.
rake rcqa              #all tests with coverage reports  
rake rcqa:units        #unit tests with coverage
rake rcqa:functionals  #functional tests with coverage

Future
I plan to add other code quality tools to this gem in the future. Likely candidates include flog, flay, and roodi. Feel free to leave a comment if you know of another code quality tool that you think I should include.

Sunday, March 7, 2010

Rails 3: Heroku

Last week I was pleased to discover that Heroku now supports the rails 3 beta. To use it you have to switch the application stack. The main Heroku stack (Argent Aspen) runs ruby 1.8.6 which does not work with Rails 3. Heroku enabled a new stack (Badious Bamboo) which runs either Ruby Enterprise Edition 1.8.7  or MRI 1.9.1 which both support Rails 3. 


To get your Rails 3 app running on Heroku you need switch to your stack by following the Heroku stacks documentation. After you have the correct stack set up you need to make sure you have all of your gems set up in your Gemfile. I ran into issues because I use SQLite during development and I didn't have the required pg gem set up in my Gemfile.


That is all there is to getting up and running. I tried out a few of the add-ons, none of them seemed to break my app, but they did not all work quite right. The New Relic add-on reported on deployments but it still has not registered a single request. 

Update: Rails 3 beta2 breaks on heroku when the New Relic add-on is added.

Tuesday, February 16, 2010

Rails 3: Loading rake tasks from a gem

Several times in the last year I have wished that a gem could have rake tasks that would be loaded into a Rails app. I looked into it several times but kept running into dead ends with Rails 2. Since the Rails 3 beta came out I decided to try again, this time with much more success.

Basically you are trying to include a rake task in your rails app, the tricky part is you are trying to include the rake task from the gem it is inside of, which itself is being included in the rails app.

Gem file structure
my_plugin.gemspec
lib/my_plugin.rb
lib/my_plugin/railtie.rb
tasks/my_plugin.rake

lib/my_plugin.rb
module MyPlugin
  require 'my_plugin/railtie' if defined?(Rails)
end
This file is automatically included as part of including the gem using bundler. All we need to do in this file is require our railtie.

lib/my_plugin/railtie.rb
require 'my_plugin'
require 'rails'
module MyPlugin
  class Railtie < Rails::Railtie
    railtie_name :my_plugin

    rake_tasks do
      load "tasks/my_plugin.rake"
    end
  end
end
In this file we create a railtie class inside of our module, our new class has to be a descendant of the Rails::Railtie class. The 'rake_tasks' method is defined in the Rails::Railtie class, it takes a block that it then runs during the initialization of the rake environment in your app.


lib/tasks/my_plugin.rake
desc 'my plugins rake task'
task :do_something do
  puts "the rake task did something"
end
Just a really simple rake task.


Using your new rake task
After you have built your gem and included it in your rails app using bundler the task is integrated just like any of the default rails tasks.
$ rake -T
# ...
# rake doc:rerails    # Force a rebuild of the RDOC files
# rake do_something   # my plugins rake task
# ...

$ rake do_something
# the rake task did something

Resources
http://weblog.rubyonrails.org/2010/2/9/plugin-authors-toward-a-better-future
https://gist.github.com/af7e572c2dc973add221

Sunday, February 7, 2010

Rails 3 beta: First impressions on a new app

Initial application creation
Initial application creation is as easy as it has always been. The output is formatted a little better and you can create an app with a path instead of just a subdirectory name. A .gitignore file is created automatically as well as a few .gitkeep files on directories that don't start out with files in them, a really nice touch for those of us who use git.


script/* replaced by script/rails
This takes a little getting used to if you are used to the old script commands. Stuff like "script/console" doesn't work any more, it has been replaced by "rails console" or "rails c" if you prefer the shorthand version. "rails --help" will be your friend until you get used to the new commands.


Generators
The new generator system seems to be very well thought out and has all kinds of great new features if you want to modify templates or write your own generators. Even if you are just running the default generators things have improved a bit. The default templates have improved, for example div tags instead of p tags and use of a form partial instead of duplicating code in the edit and new views.

Testing
Testing out of the box does not seem to have changed much. The main thing I noticed is that most of the major testing tools are not yet working with the rails 3 beta. I tried out shoulda, rspec, and cucumber all without success.

Monday, December 28, 2009

Interesting Rails Methods: update_attribute

Method: update_attribute
Module: ActiveRecord::Base
Documentation: Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records.

Notes:
This method actually does far more than just update an attribute. It updates the whole object without validations. This is fine if you just retrieved the object from the database but it can be a disaster if you have modified other attributes on the object.

Given:

Article.find(1)
#<Article id:1 title:"title" body:"first article">

Safe usage of update attribute:

article = Article.find(1)
article.update_attribute(:title, "new title")
Article.find(1)
#<Article id:1 title:"new title" body:"first article">

Unsafe usage of update attribute:

article = Article.find(1)
article.body = ""
article.update_attribute(:title, "new title")
Article.find(1)
#<Article id:1 title:"new title" body:"">

Wednesday, October 7, 2009

4 Ruby gems that will improve your rails app

These four gems have helped my team improve the quality of our code. We weren't writing bad code before but these tools made it possible for us to take our code to the next level.


Flog
Flog helps you analyze the complexity of your methods. It looks at the number of assignments, branches, and calls in a method and creates a complexity score for each method. The lower the score the less complex the method is, generally making it easier to read, test, and refactor.


Flay
Flay analyzes code for duplication. It looks for structural similarities so things like variable names and whitespace won't keep it from detecting duplication in your code.


Roodi
Roodi parses your code and gives warnings on several different code design issues. Roodi includes a few different measures of code complexity such as cyclomatic complexity, line count, and parameter count as well as some useful lint style checks.


Rcov
Rcov is a code coverage tool for ruby, it shows you what code was run during your tests. While that doesn't guarantee that you tested all of your boundary conditions it does go a long ways in giving you confidence in your test coverage. My teams threshold for code coverage is 100%, anything less is treated the same as a failing test. If you are planning on using rcov with a rails app I would suggest the rails_rcov plugin.


Bonus FREE rails plugin
When my team runs tests on our apps we use rails_quality a plugin I wrote that runs all four of these gems during the testing process. Any output that is outside of the thresholds we have set is treated the same as a failing test. I would recommend this practice to anyone. It will make your code better and it pays off way earlier in the development cycle than you expect.

Thursday, October 30, 2008

Upgrading rails apps without downtime

I recently worked on an application that took messages from internal applications and queued them up before sending them to an external vendor. The application was built because the messages were important enough that loosing any messages sent during vendor downtime was not an option. Since all applications involved were using rails it was an obvious choice to develop the queuing app in rails and use a REST api to transfer the data into the queue.

The queue app went together quite nicely and everything was going smoothly until it went live and updates were needed to fix some bugs. Since the queuing app was the method for handling downtime outside of the main application it wasn't safe for the queue to go down while the main application was still up. Out of necessity I quickly came up with a solution.

The final solution consists of running more than one mongrel cluster, preferably on different servers. Proxy to all of those clusters from the apache instance that is serving the main application. This provides redundancy as far as the mongrel clusters are concerned and if the main apps apache server is down the application won't be generating any messages to be queued.

To upgrade the queuing app without downtime upgrade the code behind one of the clusters and restart that cluster, repeating until all clusters have been upgraded. This works very nicely, but it does require careful development to ensure that each update is compatible with the previous version of the application.