Tuesday, February 15, 2011

Using Sinatra with Bundler to deploy on Heroku

I decided to try using sinatra for a small project I started the other day. I normally work in rails and host my personal projects on heroku. Since rails 3 came out I have also gotten hooked on bundler. I could not find any single source that documented how to use all of these together nicely. Here is how I got it to work.

Gemfile

The gemfile is pretty basic, set a source for gems and include the sinatra gem.
source :rubygems
gem 'sinatra'

config.ru

This is the rackup config file which sets the app up to run in rack.
require 'rubygems'
require 'bundler'

Bundler.require

require './myapp'

run MyApp

myapp.rb

This is the sinatra file. Note that I defined a class (MyApp). This is very important because our config.ru needs the class as a handle for the 'run MyApp' call. An alternative would be to use "run Sinatra::Application" in your config.ru file.
class MyApp < Sinatra::Base
  get '/' do
    'Hello world!'
  end
end

Running locally

First make sure rack is installed, then run the following commands in the root folder and the app should be up and running locally.
bundle install
rackup

Deploying to Heroku

Just run the following commands in the root folder and the app should be up and running on Heroku.
git init
git add .
git commit -m 'Initial version of MyApp'
heroku create
git push heroku master

Additional resources

Sunday, January 23, 2011

Easy data caching in Rails 3

Three common forms of caching

There are 3 types of caching that are very commonly talked about in the rails community; page caching, action caching, and fragment caching. All of these are well documented and are great ways to cache varying amounts of content for your pages.

Is that all the caching I need?

Caching at the view level is great but it isn't necessarily the best fit for every situation. In some cases it may be easier to cache data at a lower level. Perhaps you want to cache the results of an external data request for a given period of time. None of the view caching methods would be a really great fit.

Lower level data caching

Rails 3 actually has a great method for caching data at a lower level than the view. It even uses the same caching store as action and fragment caching. ActiveSupport::Cache::Store allows you to store any serializable Ruby object. Rails even provides an already initialized cache store via Rails.cache.

Example usage and code

I used this on www.checkthesock.com to cache METAR queries. I was using current_metar a gem I built that pulls metar data from ADDS. I made a model called CachedMetar to return cached results to the rest of my application.


Code walk through

This model basically returns the result of the block argument to Rails.cache.fetch the first time it is called. Any time it is called within the next 5 minutes it returns the value that was cached the first time. Everywhere I had previously been calling CurrentMetar::Metar.get_metar("ICAO code") I switched to call CachedMetar.metar("ICAO code") and that was all it took.

Testing

Testing is actually surprisingly easy. I used shoulda and mocha and here is what I ended up with.


Reference

Friday, January 21, 2011

SEO friendly maps with jQuery

In my free time I am working on a social networking site for RC pilots. I have information pages for various RC airfields and I was looking for a good way to display a listing of the fields. Putting markers on an embedded google map is a great way to display this type of data to users. The method I have seen recommended for this is to make separate list and map views. I don't really think that is a great user experience though.

The main reason making two pages is suggested is that maps require many lines of code and JavaScript functions that will dilute your content. The solution I arrived at was to use as little javascript as possible to generate my map. I ended up accomplishing this by using javascript to parse the content of the page to generate the markers.

To be able to easily parse out the data I wanted to display on the map I ended up making my own microformat. I put a class of field on the div that contained each field I was showing on the page. In that div I put the content that I wanted to display in the information popup for each marker. Then in that div I put two spans that contained the latitude and longitude and gave them each a class. The results ended up looking like this:


Then I wrote some javascript to parse this microformat and generate markers for my map. I used jQuery selectors to select each field in the html. For each field the latitude, longitude, and html contents are selected. Then the add_marker method is called to setup the marker with that data. After the marker is created I hide the field div.


Users with javascript will see a map with a bunch of markers that have an information bubble when clicked on. Users that do not have javascript enabled will see a list of field information. The textual content is the same for both users, the users with javascript just get an improved experience.

Go to www.checkthesock.com/fields to see the end result.

Monday, September 20, 2010

Getting over assert_difference

For quite a while now I have been using assert_difference or its close cousin from shoulda should_change. When I recently updated to a recent version of shoulda I noticed that they had deprecated should_change. The note in the shoulda documentation says the following: "This macro was deprecated because these tests aren’t as valuable as alternative tests that explicitly test the final state."

Ok, now what to do? assert_change is super easy to use, but does it really ensure that the desired action is actually happening? For example:

This example test asserts that the number of User objects in the database has increased by 1. No real guarantee that it was actually the User object we were interested in creating.

Lately I have been trying to be a little more explicit about what is actually happening. It is taking a little while to get used to doing things this way but the results have been satisfying. Here is an example:

This example test asserts that a User object is getting assigned to the @user instance variable and that User object is no longer a new record.

Wednesday, September 8, 2010

Code Readability: Quick, Millions or Billions?

3193490646

It is really easy to get the order of magnitude wrong on a number in code. I had settled into the habit of carefully counting my digits to make sure it was right until one of my co-workers pointed out a neat feature of ruby.

Ruby allows underscores to be inserted into numbers between any two digits. The underscores are purely cosmetic and do not affect the value of the number. This feature allows a developer to use underscores as an accountant might use commas.

3193490646      # standard representation of a number in ruby
3_193_490_646   # same value, much more readable

One less excuse for order of magnitude errors when using ruby.

A little looking around did not find any similar functionality in other languages, I checked into C/C++, Smalltalk, Python, Perl, PHP, Java, Javascript, Lisp, and Erlang. I am very curious to know if anyone knows of another language or particular implementation of one of the listed languages that supports similar functionality.


Thanks to Dallas Reedy for introducing me to this awesome feature of Ruby

Sunday, April 4, 2010

Rails Code Stats gem

When rails 2.2 came out it added some syntactic sugar by implementing a declarative block syntax for tests. The syntax for this looks like this:

test "make sure something really critical happens" do
  #code that tests for something really critical
end

While this syntax update is great some of the tools that come with rails still haven't been updated to handle it nicely. The stats rake task which outputs basic code statistics such as lines of code and methods per class still doesn't count these tests. In the past I just copied the rake tasks code and made a new rake task that could handle the new syntax as well as the format shoulda uses. After I started playing around with rails 3 and figured out how to put rake tasks in a gem I decided to write a gem that would generate an improved stats output.

Introducing Rails Code Stats

For this gem I didn't just copy the code and slightly improve the output. I refactored the code to clean things up as well as making it easier to extend functionality. One of the main changes was separating the code that calculates the stats from the code that displays the stats. Currently it still just outputs to the command line, but I intend to add the ability to have it output a HTML version as well. In addition to the new test syntax introduced in rails 2.2, I also added support for shoulda's test syntax and improved the code so that it should be quite trivial to add support for another test method syntax. Installing this plugin is as easy as adding the following to your rails 3 applications Gemfile.

gem 'rails_code_stats'

I am contemplating suggesting to the rails core team as an alternative to the current rails stats task. It seems that it fits with where rails 3 is trying to go, if you can easily swap out DB persistance layers and javascript engines why not modularize the code statistics tool as well. Please comment if you have any suggestions on improving this gem.

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.