Smashing Magazine - we smash you with the information that will make your life easier. really.
10 Useful Tips For Ruby On Rails Developers
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.
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"
endWhat’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 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
...
end4. 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.
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.
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
- 9ee8bc427d947. 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 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:
- GitHub has a most-watched projects page, which is a great place to start.
- Similarly, RubyInside’s monthly What’s Hot on Github and
- the GitHub blog’s Rebase series both feature selections of interesting work from the website.
There’s also a whole universe of Rails training:
and news aggregators:
- follow ruby_news on Twitter,
- subscribe to Ruby Inside,
- subscribe to Ruby Flow.
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)
- 75 Comments
- 1
- 2February 25th, 2009 12:27 pm
Meh.
- 3February 25th, 2009 12:32 pm
Thanks for the information – will definitely use this
- 4February 25th, 2009 12:33 pm
As always, great job guys!
- 5February 25th, 2009 12:33 pm
Railscast is another great place for RoR training.
- 6February 25th, 2009 1:09 pm
Very helpful, Im taking my first real dive into RoR, think this will help!
- 7February 25th, 2009 1:19 pm
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! - 8February 25th, 2009 1:24 pm
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.
- 9February 25th, 2009 1:33 pm
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!
- 10February 25th, 2009 2:24 pm
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 :)
- 11February 25th, 2009 2:37 pm
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. - 12February 25th, 2009 3:28 pm
Nice!! Thanks for sharing
- 13February 25th, 2009 5:39 pm
Hey, thanks for the Rebase shoutout! :)
- 14February 25th, 2009 5:49 pm
really nice one here! i´d love to read more about ruby and/or rails. cheers!
- 15February 25th, 2009 5:53 pm
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.
- 16February 25th, 2009 7:23 pm
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.
- 17February 25th, 2009 7:42 pm
Awesome guys!
It’s good to see some stuff on rails!
keep up the good work SM! - 18February 25th, 2009 7:45 pm
lol never tried ruby on rails..heard of it a lot but I don’t think its for amateurs like me :P
- 19February 25th, 2009 7:48 pm
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.
- 20February 25th, 2009 8:05 pm
I could never wrap my brain around Rails, and I still can’t. I guess ya can’t teach an old dog new tricks.
- 21February 25th, 2009 8:08 pm
useful tips alright!
- 22February 25th, 2009 10:45 pm
Nice one guys keep up the good work…
- 23February 26th, 2009 12:46 am
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 :)
- 24February 26th, 2009 1:31 am
Smashing tips thanks.
They make a change from the usual regurgitated list of tips for Rails beginners.
- 25February 26th, 2009 1:43 am
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!
- 26February 26th, 2009 2:27 am
what do you guys think about django?
- 27February 26th, 2009 3:19 am
really great and useful info…
thanks…
- 28February 26th, 2009 3:25 am
Do you have any information / tips on how RoR and (Adobe) Flex work together?
- 29February 26th, 2009 4:38 am
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. - 30February 26th, 2009 5:35 am
Rapt is a great tool for searching plugins. Get it by
gem install rapt
allows things such as
rapt search calendar
…returns list of discovered plugins with installation info
- 31February 26th, 2009 6:15 am
11) don’t use ruby
- 32February 26th, 2009 7:34 am
Should add http://www.railscasts.com to railsenvy and peepcode. http://www.rubyplus.org is worth a mention too.
- 33February 26th, 2009 11:56 am
I need to get going learning some RoR! Thanks SM
- 34February 26th, 2009 3:15 pm
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?
- 35February 27th, 2009 2:14 am
Thanks for free tools. realy great. I translate to MX and publish to my web sites this article
- 36February 27th, 2009 2:41 am
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!
- 37February 27th, 2009 3:17 am
#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.
- 38February 27th, 2009 10:40 am
good tips, simple to read :)
- 39February 27th, 2009 1:11 pm
Hi,
Great Tips, but how could you exclude RailsCasts.com by Ryan Bates from your list?
also The Pragmatic Bookshelf http://www.pragprog.comThanks,
Erez
- 40February 27th, 2009 5:10 pm
edit: nevermind…
- 41February 28th, 2009 3:01 pm
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/ - 42March 5th, 2009 8:58 pm
Nice article. !
- 43March 6th, 2009 12:20 am
Hi SM,
Thanks for the article! nice job! - 44March 9th, 2009 5:34 am
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
- 45March 12th, 2009 5:52 am
Raivo Pommer
raimo1@hot.eeOECD-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.
- 46March 20th, 2009 2:46 am
The article is great! Thanks :-)
BTW: I think the comment from zumwinkel is just spam! Has nothing to do with the article. - 47March 22nd, 2009 3:51 am
For 7 use the settingslogic gem http://github.com/binarylogic/settingslogic/tree/master
- 48March 29th, 2009 6:24 am
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 !
- 49April 16th, 2009 9:25 am
its a great article very informative and great tips!!!!
- 50April 16th, 2009 1:57 pm
Thanks for the tip on Yaml_db
- 51April 19th, 2009 12:12 pm
Well ! The tools you gave are great as always :) thanks
- 52May 19th, 2009 5:01 am
Thank you for posting nice tips on ruby on rail development it’s use full in programming.
- 53May 25th, 2009 6:45 am
If HAML is too scary looking, but you don’t like angle brackets, check out Erector.
- 54June 8th, 2009 3:07 am
Thanks for some interesting information.
Much appreciated.
brian
- 55August 25th, 2009 9:36 pm
Veri nice tips to develop an application. Thanks alot…
- 56August 27th, 2009 11:26 pm
love this article, thanks.
- 00
There are no trackbacks at this time. If you are interested in leaving a trackback, please use this URL.
Leave a Comment
Make sure you enter the * required information where indicated. Please also rate the article as it will help us decide future content and posts. Comments are moderated – and rel="nofollow" is in use. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!
Interact
Popular
- 100 Wordpress Themes
- Photoshop Tutorials
- Fantastic Wallpapers
- 40+ Excellent Freefonts
- Dual-Screen Wallpapers
- Wordpress Themes for 2009
- Illustrator Tutorials
- Incredible Free Icon Sets
- High-Quality Free Fonts
- 30 Scripts For Galleries
- Photoshop Text Effects
- Useful Icon Sets
- Web Design Trends
- iPhone Wallpapers
- Before Launching a Website
- CSS Layouts And Templates
- Photoshop Actions
- Stunning Pictures and Photos
- Fantastic HDR Pictures
- Logo Design Tutorials
- Free Design Templates
- 10 Mistakes In Logo Design
- Photoshop Custom Shapes
- 40 Creative Design Layouts
- 8 Layout Solutions
- 53 CSS Techniques
- Photography Techniques
- Black & White Photography
- Styling Design Elements
- CSS-Based Forms
- 50 jQuery Techniques
- 50 Portfolio Websites
- 50 CSS Techniques
- Creative Logo Designs
- Desktop Wallpapers
- 25 Open Source Mac Apps
- 50 Free Icon Sets
- The Big Showcase Of Online T-Shirt Stores - http://bit.ly/5Tq8uA
- @ilmv oh ok then ;)
- @ilmv no, the SM Book will not be out of date :) We made sure it contains universal design, usability and marketing principles.
- Apple ad bombing Windows 7 on Google - http://bit.ly/28ctPq
- Atatonic - a fresh CSS framework - http://bit.ly/4oOV2w (via @umutm)
- @HrvojeKC yes, that's an interesting idea. Maybe when the waiting is over, we'll write a detailed post about it.







Great useful tips. Thanks SM!