Advertisement

10 Awesome Ruby on Rails Techniques to Get You Started

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

Rails has seemingly set the web development world on fire these past few years. Popular web applications like Basecamp and Twitter have pushed Rails into the limelight as an excellent framework that any programmer (or even non-programmer) can quickly use to create applications.

One of the most popular aspects of Rails is how easy and intuitive it is to start using right out of the box. Here are 10 tips that beginners can use to help with getting started with the powerful framework.

1. Utilize Source Annotations

If you're a beginning programmer, you'll soon realize that a major part of writing code is correctly writing source annotations and comments. While this tip isn't necessarily Rails specific, it sure does pertain to solid rails coding. If you're going to annotate your code, use these aptly named keywords:

  • TODO - Used to show code that is incomplete or needs some work
  • FIXME - Used to show code that is broken or buggy
  • OPTIMIZE - Used where further optimizations need to be done

Using these function while programming Rails is especially helpful as Rails allows for adding rake tasks that help you search the code for all the occurrences and prints them out with the file name, line number, and the description.

rake notes
app/controllers/contacts_controller.rb:
  * [ 3] [TODO] factor out model verification to a filter
  * [ 4] [OPTIMIZE] optimize this
  * [ 5] [FIXME] it's broken

Perfect for finding those little things that need some TLC within your code.

2. Monitor Your Apps!

As your Rails applications start to become more complex, you'll start to notice that some processes might need a tad more TLC in terms of optimization. In order to find those little bugs and errors in your code, try using the excellent Relic RPM to monitor your applications. Relic RPM gives you a chance to monitor all of the processes of your application, and gives you visual graphs and other helpful information to really get a handle on the processes that are causing slowness in your app.

The RailsTips blog has an excellent review of Relic RPM. Analytics are indispensable for developing successful and efficient Rails applications.


Photo by helmet13

3. Group Operations in a Transaction

ActiveRecord is the handy persistence engine that allows you to do many cool things with data and logic. One of the really handy things that ActiveRecord allows you to do is to group multiple inserts in a single transaction. Zen and the Art of Computing gives an excellent example of this technique.

Instead of:

 my_collection.each do |q|
   Quote.create({:phrase => q})
 end

Use:

Quote.transaction do
 my_collection.each do |q|
   Quote.create({:phrase => q})
 end
end

or for rolling back the whole transaction if any insert fails, use:

Quote.transaction do
 my_collection.each do |q|
   quote = Quote.new({:phrase => q})
   quote.save!
 end
end

Photo by Wonderlane

4. Sift Through Page Elements with RJS

One of the incredibly useful aspects of Rails is the built-in support for Javascript and AJAX integrations. They even include a templating language for Javascript called RJS templates. RJS allows the programmer to easily update multiple elements of the page with AJAX.

To take the example a step further, you can use RJS to iterate through page elements and dynamically change them using AJAX. You can even change the elements on the page through CSS queries. For example, you could do something like:

	page.select('#cssid li').each { |item| item.hide }

Nifty, eh? Sifting through the elements can be incredibly powerful to use inside your application's interface.


Photo by Phillip Ritz

5. Cache Unchanging Data at Application Startup

Performance may not be a huge issue in the development stages of learning Rails, but eventually you'll want to reach a point where your app is running quickly and smoothly. Caching is an excellent way to speed up an application. RubyInside has an excellent tip on how to cache data that isn't changed often.

"If you have data that doesn't change between application restarts, cache it in a constant somewhere. For example, you might have a YAML or XML file in /config that stores application configuration data, and you could load it into a constant in environment.rb, making lookups quick and easy application-wide."


Photo by flydime

6. Practice to Become a Rails Ninja

While it's easy to get started with Rails, it takes work to become a pro. Many times beginning programmers believe that frameworks like Rails take out that learning curve, allowing them to quickly become experts. It never works that way. The Framework is only a tool to help you overcome many of the repetitive tasks associated with Ruby.

Jay Fields knows that mastering Rails isn't easy. In fact he goes on to say the following:

"The screencasts and pictures don't lie. It is easy to learn Rails and quickly become productive. However, the dirty little secret is that it's very hard to be come an expert at utilizing Rails.

"Rails provides many helpers that make your life easy. But, you can't entirely hide the fact that you'll need to be proficient with Ruby, JavaScript, YAML, and SQL. Just like Rails, getting started with any of the above languages is easy, it's mastering them that takes time and effort.

"You should always remember that the biggest aspect of becoming an expert is time and practice. Rails is a great framework, but it can only help you so far without doing any extra learning."

7. Move JavaScript to the Bottom

This is actually a great rule of thumb for just about any language, and it's good to remember if you're just getting started with Rails as well. Moving the Javascript includes to the bottom of the template (right before the tag) allows all the HTML to be rendered, so the Javascript doesn't slow the visual loading of the page.

It's a simple tip, but it can make a big difference.


Photo by visualpanic

8. Watch Your Form's Attributes

Forms are a major part of web development, with nearly every web application relying on forms for collecting user information, signups, and a myriad of other uses. However, sometimes new programmer don't always use forms very securely. FortyTwo has an excellent example of how to add a dash of security when you're building your forms.

<% form_for :user, @user, :url => {:controller => "users", :action => "update_email", :id => @user.id} do |f| -%>
	<p>
		<label for="user_email">Email: </label> <%= f.text_field :email %>
	</p>
	<p>
	   <%= submit_tag "Change" %>
	</p>
<% end %>

Then inside the controller we update the user's mail:

def update_email
   #all access and db logic handled with before filters
   if @user.update_attributes(params[:user])
     flash[:notice] = "We did it"
   else
   	 flash[:alert] = "Nope. We didn't make it"
   end
end

"When you are doing bulk updates like User.new(params[:user]) or user.update_attributes(params[:user]) you open the door to anyone updating important attributes that you only have (or should) have access to. In the above example someone can append user[:purchased_credits] = 1000 and make himself a gift.

Always secure your model's important attributes from bulk updates using attr_accessible or @attr_protected* in the model declaration. And write tests about it. Always!"


Photo by 96dpi

9. Use to_param for SEO-Friendly Slugs

If you're going to make your application public, why not make it as accessible as possible to search engines? Not only does this help the end user by eliminating variable gobbledy-gook in the URLs, but it also helps search engines figure out exactly what the page is going to be about.

You can achieve clean URL goodness with Rails with the slick to_param function.

	class Article < ActiveRecord::Base

	  def to_param
	    id.to_s+'-'+title.downcase.gsub(' ', '-')
	  end

	end

This automatically takes your title and makes a "slug" for it in the model of your application. Simple and easy.


Photo by tanakawho

10. Populate a Database with Test Data

After you're done writing your application, you're going to want to test it to make sure there isn't an abundance of bugs and other problems with what you've done. A good way to achieve this is to create a database and plunk a bunch of test data into it, so you can play with a demo site.

The excellent Railscasts site has a strong example of how to pull this off on an episode of their screencast. You can download the full source code along with the screencast and helper documentation. An excellent resource for any Rails developer, novice or pro.


Photo by 96dpi
  • Subscribe to the NETTUTS RSS Feed for more daily web development tutorials and articles.

Glen Stansberry is a web developer and blogger who's struggled more times than he'd wish to admit with CSS. You can read more tips on web development at his blog Web Jackalope.

Liked this post? Vote for it on Digg below. Thanks!


Advertisement