10 Useful Tips For Ruby On Rails Developers

Advertisement

By Greg Borenstein and Michael ‘MJFreshyFresh’ Jones

Rails is an model-view-controller Web framework written in the Ruby programming language. One of its great appeals is being able to quickly crank out CRUD-based Web applications. A big advantage of Rails over other frameworks is that it values convention over configuration. If you follow the correct conventions, you can avoid lengthy configuration of files, and things just work! Therefore, you spend less time writing boring config files and more time focusing on business logic.

Ruby on Rails logo

Now, we love Rails. But don’t get us wrong. Like any tool, it’s not the perfect solution to every problem. A lot of the biggest complaints people have about the framework come from using it in situations where something simpler, smaller and more lightweight would do just fine. We love Sinatra for anything with minimal server-side involvement. Merb is another excellent minimal framework. And nothing beats apps that run completely in the browser with JavaScript: they can be deployed nearly for free, can scale almost infinitely and never have to be restarted.

In the overview below we present 10 useful tips, ideas and resources for Ruby on Rails-developers (both newbies and professionals). Please feel free to share your tips, ideas and suggestions in the comments to this post!

1. Plug-Ins Save Time

Rails has a well defined plug-in structure that enables you to easily install and use plug-ins in your application. David Heinemeier Hansson, the father of Rails, once stated that he uses five to six plug-ins in each Rails application.

There’s an old nugget of developer wisdom that “the best code is no code at all.” Part of what makes us so productive when developing in Rails is that all the code that we don’t have to write because someone else in the community has already written a plug-in that provides the functionality we need.

There are a few ways to install a plug-in in Rails, however the most common is using script:

# Install from a git repo
script/plugin install git://github.com/mislav/will_paginate.git

# Install from a url
script/plugin install http://topfunky.net/svn/plugins/calendar_helper

You can save yourself a ton of time and hassle by becoming good at searching the Web (and especially the almighty GitHub). A couple of places to find plug-ins are Core Rails, Railsify and Rails Plug-in Directory. Need to integrate with an existing API or consume some kind of standard format data? Need tagging, pagination, or another common Web application feature? Odds are that some great Rails or Ruby developer out there already has a project going that will get you at least most of the way there.

2. Testing is Fun and Easy with Rspec

For most people, the word “test” brings back scary memories of school exams. When working with Rails, however, automated testing can make your development experience much more enjoyable. While lots of people have strong, nearly religious, opinions about them, at their core, automated tests are just little helper programs you write that run bits of your main code to make sure they do the right thing. When done right, testing will improve your workflow and increase your confidence in the results.

Rails ships with a test framework baked right in, but for the last couple of years all the cool kids have been using an alternative called Rspec. Rspec’s biggest advantage is its syntax for specifying tests:

describe "My Cool library" do
  before do
    @cool = Cool.new
  end

  it "should be full of penguins." do
    @cool.get_penguins!
    @cool.penguin_count.should == 10
  end

  it "should melt if it gets too warm"
end

What’s great about Rspec’s syntax is how much English it uses. The describe block that sets the context and each assertion within it takes strings that you use to explain what your code should do. Often, this is the most important stage: you sit down to write the assertion, getting as far as you can, and then you think, “Right, what should this code actually do then?”

Because Rspec lets you leave off the block that implements the assertion (as in the second melt example), you can quickly brainstorm all of your functionality, and then go back and implement the tests later as you write the code. In the meantime, Rspec will consider those tests as “pending” and give you little reminders about them in your test runs.

Besides helping you write code in the first place, another great thing about tests is that, once you have enough of them, they let you see how all of your code is related, making it easy to know if your recent change broke anything else in your application. Rspec makes it easy to get good test coverage through the use of custom generators that create the tests right along with the rest of your code:

$ script/generate rpsec_scaffold MyModel

Once you’ve got tests to ensure that the basic functionality works successfully, you can make changes and add new code with confidence without worrying about introducing invisible bugs. As long as you run your tests regularly, you’ll know as soon as you break something. And as GI Joe taught us, knowing is half the battle!

3. Save Time, Use Rake

Projects often include more than just application-specific code. Sample data have to be created, Web services have to be queried, files have to be moved, code snippets rewritten, etc. Resist the urge to shell script or to cram in a migration or controller. Use Rake. It rocks!

Rake

Rake is a build tool written in Ruby, very similar to make. Rails projects have several Rake tasks already defined; to see these, run the rake -T command.

macbook$ rake -T

rake data:bootstrap		# load in some basic data [caution: will nuke and replcace cate...
rake db:create:all		# Create all the local databases defined in config/database.yml
rake db:drop			# Drops the database for the current RAILS_ENV
...
rake ts:run				# Stop if running, then start a Sphinx searchd daemon using Thi...
rake ts:start			# Start a Sphinx searchd daemon using Thinking Sphinx's settings
rake ts:stop			# Stop Sphinx using Thinking Sphinx's settings

Adding your own Rake tasks is quite easy. In the example below, you see that the task is name-spaced and has a description and task name, allowing you to write in Ruby.

namespace :data do
  desc "load in some basic data [caution: will nuke and replcace categories, categorizations and inventory items]"
  task :bootstrap => :environment do
    # clean out existing:
    [Category, Categorization, InventoryItem].each{|m| m.find(:all).each{|i| i.destroy}}
    InventoryItem.create! :name => "Compass"
    c = Category.create! :name => "Basic Apparel"

    ["Men’s Heavyweight Cotton T",
    "Men’s Heavyweight Polo",
    "Women’s Organic Cotton Fitted T",
    "Women’s Fitted Polo",
    "Children’s T-Shirt",
    "Jr’s Distressed Hoodie",
    "Hemp Messenger Bag"].each do |name|
      c.inventory_items.create! :name => name
    end

   ...

end

4. Track Application Exceptions

Exceptions happen, and when they do, you want to know about them! Your client shouldn’t be the one telling you that a problem has occurred; you should already be aware of the issue and working to resolve it. Exception notification has been available in Rails for a while. There are exception notification plug-ins that make it easy to be notified. However, some services such as Hop Toad and Get Exceptional add a lot of value to your application.

Screenshot

Both of these services are easy to install and provide a great UI for tracking your exceptions. You can even sign up for a free account to try things out.

By centralizing the application exceptions, you are able to see how frequently these exceptions occur, what environment they occur in (a particular browser? a particular location?), what parameters were present and the full stack trace. This centralization of data helps you see patterns and resolve the issue more quickly, which results in a better application and happier users.

5. Mix and match between frameworks and servers with Rails on Rack

As of version 2.3, Rails runs on top of Rack. Rack makes it possible to mix and match between Ruby Web frameworks and servers. If you’re using a framework that supports it (like Rails, Sinatra, Camping, etc), you can choose from any of the servers that do also (Mongrel, Thin, Phusion Passenger, etc.), and vice versa.

Screenshot

In addition to introducing all kinds of new options for deployment, this change means that Rails now has access to the exciting world of Rack middleware. Because Rack lives at the intersection of your app and your server, it can provide all kinds of common functionality directly. A great example of this is Rack::Cache.

Rack::Cache provides a caching layer for your application that you control simply by sending the correct headers in your responses. In other words, all you have to do is install a bit of code in the Rack config file:

require 'rack/cache'

use Rack::Cache,
  :metastore => 'file:/tmp/rack_meta_dir',
  :entitystore => 'file:/tmp/rack_body_dir',
  :verbose => true

And make sure your controller actions send the right headers (for example, by setting request.headers["Cache-Control"]) and Bam!, you’ve got caching.

6. Easy Data Dumping

You’ll often need to get data from production to dev or dev to your local or your local to another developer’s local. One plug-in we use over and over is Yaml_db. This nifty little plug-in enables you to dump or load data by issuing a Rake command. The data is persisted in a yaml file located in db/data.yml. This is very portable and easy to read if you need to examine the data.

rake db:data:dump

example data found in db/data.yml

---
campaigns:
  columns:
  - id
  - client_id
  - name
  - created_at
  - updated_at
  - token
  records:
  - - "1"
    - "1"
    - First push
    - 2008-11-03 18:23:53
    - 2008-11-03 18:23:53
    - 3f2523f6a665
  - - "2"
    - "2"
    - First push
    - 2008-11-03 18:26:57
    - 2008-11-03 18:26:57
    - 9ee8bc427d94

7. Keep Your Constants in One Place

All applications have constants, variables that are defined with data that don’t change, such as the name of the application, the tagline, values for crucial options, etc. We use the Rails initializer feature to define a config/initializers/site_config.rb for housing these constants. By using this convention, all developers on a project know exactly where to look for the constants and can quickly make changes.

Many people have questions about when to put a constant in the site_config.rb instead of the class it is used in. For a constant that are only used in a single class, we suggest putting it in that class. However, if the constant is used in more than one location, put it in the site_config.rb. For more on constants, have a look at Rubylearning.

# File config/initializers/site_config.rb

REPORT_RECIPIENT = 'jenn@scg.com'
REPORT_ADMIN = 'michael@scg.com'

8. Console for Working on Code

Sometimes you may have code that you’re curious about. Will it work this way? What’s the output? What can I change? Rails ships with a wonderful tool called console. By running script/console you will enter an interactive environment where you can access your Rails code just as though the application were running.

This environment is incredibly helpful. It is often used in production environments at times to quickly peek at data without having to log in to the database. To do this in a production environment, use script/console RAILS_ENV=production:

macbook$ ./script/console
Loading development environment (Rails 2.1.1)
>> a = Album.find(:first)
=> #
>>

9. Ugly Views Getting You Down? Try Haml.

Views are how your Rails application generates the HTML pages your visitors actually see and use. By default, Rails uses the ERb templating system to let you embed bits of Ruby in your markup so that you can insert your data as needed. However, recent versions of Rails let you take your pick of templating languages, and nowadays the Ruby interwebs have been all abuzz about an alternative system called Haml.

HAML

Haml is marketed as “markup Haiku.” Its CSS-inspired syntax lets you focus on the semantics of your data rather than worrying about closing all the angle brackets that come with using ERb and HTML.

For comparison, here’s a bit of markup in standard ERb:

<%= print_date %>
<%= current_user.address %>

<%= current_user.email %>
<%= h current_user.bio %>

And here’s the equivalent in Haml:

#profile
  .left.column
    #date= print_date
    #address= current_user.address
  .right_column
    #email= current_user.email
    #bio= h(current_user.bio)

Haml’s not for everyone, and many people will find this syntax quite alien. But if you value concision and are fluent in CSS, Haml may be just the ticket.

10. Know Where to Watch What’s Happening in Rails

Rails and Ruby both have large and active communities that constantly generate changes, improvements and new projects. Trying to keep up with all the activity can be daunting, but it’s essential if you want to benefit from the community’s best work and continue to increase your Rails and Ruby knowledge.

Thankfully, a number of sources aggregate some of the most important activity:

There’s also a whole universe of Rails training:

and news aggregators:

Another avenue is the Rails Core mailing list and the #rails-core IRC channel.

About the authors

This guest post was written by Greg Borenstein and Michael ‘MJFreshyFresh’ Jones, lead Ruby developers for StepChange Group. StepChange designs, develops and manages social media widgets and Facebook applications in partnership with leading brands and agencies. Outside of work, Greg builds drum-playing robots and other hardware hacks, and MJ leads a local group of Unicycle-borne pirates. They live and work in beautiful, moist Portland, Oregon.

(al)

↑ Back to top

Crystal Beasley is a product designer at Mozilla. She loves to write on her own blog and tweets @skinny.

  1. 1

    Great useful tips. Thanks SM!

    0
  2. 2
  3. 3

    Thanks for the information – will definitely use this

    0
  4. 4

    As always, great job guys!

    -1
  5. 5

    Railscast is another great place for RoR training.

    1
  6. 6

    Very helpful, Im taking my first real dive into RoR, think this will help!

    1
  7. 7

    I have been using Ruby and Rails for quite some time, and got a fair few sites under my belt.
    Having said that, I found this article very informative, the Rails community moves at such a pace, its sometimes hard to keep up. Thanks for bringing me up to date!

    2
  8. 8

    Doing integration testing with Cucumber should also be mentioned. Cucumber allows you to write plain text stories that set up conditions and test expectations by interfacing with your application like a user would. The benefits are numerous: you test your full application stack (views, models, controllers, and interactions thereof), you can hand the feature descriptions directly to stakeholders and have them evaluate them, and it’s very easy to write and maintain.

    Along testing lines, replacing fixtures with generators like factory_girl or machinist is a good idea. Fixtures quickly become unwieldy, and being able to generate objects as you need them helps keep tests clean.

    For deployment and production use, the biggest time savers ever are Phusion Passenger and Capistrano. Passenger makes running a Rails application very simple (just a few declarations in your Apache config file and you’re good to go), and Capistrano makes deploying changes to your production server (or staging/test server, for that matter) a breeze.

    0
  9. 9

    I was introduced to HAML/SASS a while back, and I have to say, it’s quite the amazing language! Totally makes thing easier with the required indentation, and automatic closing of tags. I wish I could use it outside of RoR because whenever I have to code something for WordPress now, I think, “Darn I have to use HTML again.”

    Thanks for the tips Smashing Magazine!

    0
  10. 10

    Thanks for mentioning Ruby Inside (I’m the editor). I just wanted to highlight that Rails Inside at http://www.railsinside.com/ is more Rails specific but in the same vein :)

    0
  11. 11

    The best tip so far is the new rails 2.3 feature regarding application templates: http://railscasts.com/episodes/148-app-templates-in-rails-2-3
    Love it.

    0
  12. 12

    Nice!! Thanks for sharing

    0
  13. 13

    Hey, thanks for the Rebase shoutout! :)

    0
  14. 14

    really nice one here! i´d love to read more about ruby and/or rails. cheers!

    1
  15. 15

    Excellent list of tips. I would drop one of them though in place of a suggestion to use Machinist + Forgery. That combination has made my testing so much more enjoyable.

    0
  16. 16

    Having written a couple websites with Rails, I strongly disagree with #1: plugins are ultimately a time sink.

    Ruby already has a way to bundle library functionality: gems. You can install and upgrade them on their own and everything works great. Rails plugins always seem to have compatibility issues, and slight differences in *anything* (even tiny things that you’d think should never make any difference) between a dev box or test box or prod box kill them because the plugins are tied to the source code and not the Ruby install and OS.

    At my last company, our policy was: gems all you want, but plugins only if absolutely necessary. My only regret was that I should have used a higher threshold for “absolutely necessary”, because those we did end up needing caused way more than their share of pain.

    0
  17. 17

    Awesome guys!
    It’s good to see some stuff on rails!
    keep up the good work SM!

    0
  18. 18

    lol never tried ruby on rails..heard of it a lot but I don’t think its for amateurs like me :P

    0
  19. 19

    Great tips! I definitely need to look into Rspec as testing is painful for me. I looked into Haml but just couldn’t get away from good old familiar html syntax.

    0
  20. 20

    I could never wrap my brain around Rails, and I still can’t. I guess ya can’t teach an old dog new tricks.

    0
  21. 21

    useful tips alright!

    0
  22. 22

    Nice one guys keep up the good work…

    0
  23. 23

    I’ve done a fair bit of reading on Rails, but never taken it on board for an actual project. Every now and again, I really get the urge to do something with it. Of course it’s not perfect, but nothing is.

    Thanks for the list :)

    0
  24. 24

    Smashing tips thanks.

    They make a change from the usual regurgitated list of tips for Rails beginners.

    0
  25. 25

    Excellent feature, I love this site. I currently run three sites that use Rails, and these will be of great use.

    The widespread use of plug-ins in the Rails community is a great practice, and for me seems to emulate the outsourcing model of business i.e. site developers can focus on their core competence (their own site) and outsource common functions/features to plugins. As some plugins become popular, it allows the developers of these popular plugins to focus more time on improving them thus improving the quality of the plug in and the applications its used in. Everyone’s a winner!

    1
  26. 26

    what do you guys think about django?

    0
  27. 27

    really great and useful info…

    thanks…

    0
  28. 28

    Do you have any information / tips on how RoR and (Adobe) Flex work together?

    0
  29. 29

    Plugins can be a fantastic labour saver and a horrible time sink.
    The thing is, there’s no quality control – anyone can release a
    plugin. When you’re starting out they can save you so much
    time, but when you’re at the point where you want your code
    to be clean and efficient it’s important to make sure the plugins
    you’re using are comparable to anything you could program
    yourself.

    I’ve written a couple of plugins myself and I think the important
    thing is to focus on one thing and code it as efficiently as possible,
    making any additional bells and whistles optional. Otherwise
    you quickly run into problems getting it to work in different
    environments, with multiple configurable models etc.

    0
  30. 30

    Rapt is a great tool for searching plugins. Get it by

    gem install rapt

    http://rapt.rubyforge.org/

    allows things such as

    rapt search calendar

    …returns list of discovered plugins with installation info

    0
  31. 31

    11) don’t use ruby

    -1
  32. 32

    Should add http://www.railscasts.com to railsenvy and peepcode. http://www.rubyplus.org is worth a mention too.

    0
  33. 33

    I need to get going learning some RoR! Thanks SM

    0
  34. 34

    Great list, one question though, how the examples for haml are equivalent? in haml you’re creating a bunch of divs when in Erb
    you’re not. That’d would make the point for using haml a better one.

    Anyone know if using haml make Rails views a little slower?

    0
  35. 35

    Thanks for free tools. realy great. I translate to MX and publish to my web sites this article

    0
  36. 36

    Thanks a million for featuring Exceptional! Seen a lot of new sign ups on the back of this article, and a few new customers too. Thanks Smashing Magazine, you’re awesome!

    0
  37. 37

    #44 I don’t think there would be any real speed difference as you need to process either ERB or HAML anyway. The thing is that many find HAML really nice to work with, and can save time during development. I know this has been the case with my business.

    0
  38. 38

    good tips, simple to read :)

    0
  39. 39

    Hi,

    Great Tips, but how could you exclude RailsCasts.com by Ryan Bates from your list?
    also The Pragmatic Bookshelf http://www.pragprog.com

    Thanks,

    Erez

    0
  40. 40

    edit: nevermind…

    0
  41. 41

    Good page and very good info and tips !
    Can you add more info about satellite dishes installation tips ?
    Regards,
    Max
    http://useful-tips-and-ideas.blogspot.com/

    0
  42. 42

    Nice article. !

    0
  43. 43

    Hi SM,
    Thanks for the article! nice job!

    0
  44. 44

    step 9 is off. the complete erb code is not shown/rendering (div tags). if i did not know about haml, i would be confused because the haml code actually looks more complicated

    0
  45. 45

    zumwinkel story

    March 12, 2009 5:52 am

    Raivo Pommer
    raimo1@hot.ee

    OECD-Papiergeld

    Der Satz ist kryptisch: Liechtenstein akzeptiere die OECD-Standards für Transparenz und Informationsaustausch in Steuerfragen und unterstütze die internationalen Maßnahmen gegen die Nichteinhaltung von Steuergesetzen. So teilte es die Regierung des Fürstentums mit. Hinter diesem Satz verbirgt sich jedoch eine echte Revoulution: Liechtenstein beugt sich dem internationalen Druck – und hebt sein striktes Bankgeheimnis teilweise auf. Damit will das kleine Land sein Image von der unkooperativen Steueroase abstreifen.

    Mit den USA hat das Fürstentum bereits ein Abkommen geschlossen, wonach Informationen in Steuerfragen ausgetauscht werden können. Es tritt 2010 in Kraft. Damit wird deutlich: Das Land wird sich im Kampf gegen die internationale Steuerflucht künftig nicht mehr auf das Bankgeheimnis berufen.

    Seit Juni 2000 steht Liechtenstein auf der OECD-Liste der Steueroasen. Auf dieser schwarzen Liste zu finden sind derzeit auch Andorra und Monaco. Schärfster Kritiker des Liechtensteiner Bankgeheimnisses ist Deutschland. Denn viele Deutsche haben versucht, über den Umweg Liechtenstein dem deutschen Fiskus Steuergeld vorzuenthalten. Prominentester Steuersünder war der ehemalige Postchef Klaus Zumwinkel. Dieser wurde im Januar vom Landgericht Bochum wegen Steuerhinterziehung zu zwei Jahren Gefängnis auf Bewährung und einer Geldstrafe verurteilt.

    -1
  46. 46

    The article is great! Thanks :-)
    BTW: I think the comment from zumwinkel is just spam! Has nothing to do with the article.

    0
  47. 47
  48. 48

    You can save yourself a ton of time and hassle by becoming good at searching the Web (and especially the almighty GitHub).

    The link to GitHub is Wrong in the above block !

    0
  49. 49

    its a great article very informative and great tips!!!!

    0
  50. 50

    Damian Nicholson

    April 16, 2009 1:57 pm

    Thanks for the tip on Yaml_db

    0
  51. 51

    Adam Winogrodzki

    April 19, 2009 12:12 pm

    Well ! The tools you gave are great as always :) thanks

    0
  52. 52

    If HAML is too scary looking, but you don’t like angle brackets, check out Erector.

    0
  53. 53

    Thanks for some interesting information.

    Much appreciated.

    brian

    0
  54. 54

    Veri nice tips to develop an application. Thanks alot…

    0
  55. 55

    love this article, thanks.

    0
  56. 56

    fantastic. step by step from A to Z. Thanking you

    0
  57. 57

    It,s very useful to learn about Ruby..

    0
  58. 58

    really thanks for the useful info.

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top