Recipe 10.2. Fixing Bugs at the Source with Ruby -cw


Problem

You want to check for Ruby syntax errors without reloading your browser, and, in turn, the Rails development environment.

Solution

An easy way to check the syntax of a Ruby source file without restarting the Rails framework is to pass the file to the Ruby interpreter in syntax-checking mode using the -cw option. The c option has Ruby check your syntax, while the w option has Ruby warn about questionable code, even if your syntax is valid.

Here is an erroneous model class definition:

app/models/student.rb:

class Student < ActiveRecord::Base   def self.list_ages     Student.find(:all).map {|s| s.age }}.flatten.uniq.sort   end end

Run the file through Ruby's syntax checker:

$ ruby -cw app/models/student.rb student.rb:4: parse error, unexpected '}', expecting kEND     Student.find(:all).map {|s| s.age }}.flatten.uniq.sort                                         ^ rorsini@mini:~/Desktop/test/app/models

The output shows that there's an extra right closing bracket. The message tells you exactly what's wrong, including the line number and even a bit of ASCII-art pointing to the error. Try to get into the habit of verifying the syntax of your Ruby source before going to your browser, especially if you're just getting your feet wet with the Ruby language.

Discussion

Using the syntax checker is a great way to make sure you're supplying Rails with valid Ruby, and it's easy enough to do every time you save a file. If you're using any modern programmable text editor, you should be able to check syntax without leaving your program. For example, while editing the solution's student.rb file in Vim, you can type :w !ruby -cw in command mode, and you'll see the following within the editor:

                :w !ruby -cw -:4: parse error, unexpected '}', expecting kEND     Student.find(:all).map {|s| s.age }}.flatten.uniq.sort                                         ^ shell returned 1 Hit ENTER or type command to continue

If you're using TextMate on a Mac, you can set up a keyboard shortcut that filters the file you're working on through a command such as ruby -cw. If you're not using a text editor or IDE that offers this kind of flexibility, you should consider switching to something like Vim, TextMate, or Emacs, and learning how to customize your editor.

See Also

  • Section 10.12"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net