Five Rails Tips

6 05 2008

I’m a big fan of Ryan Bates’ Railscasts. He is holding a contest and I thought I would participate and share 5 Rails tips with the community.

Without further ado, here are my five tips.

Tip 1: Rake task to remove tildes (~) added by text editors

My favorite text editors (emacs or gedit) create files that end with a tilde character (~) as backup copies when I modify a file. Thus, after working on my rails project for a while, I have a bunch of files ending with ~ that are hanging around. At times, it can be annoying to have my directories filled with these files so I use a rake tasks to get rid of them all.

Put the following in a file called ’tilde.rake’ and save this file in your rails project under the lib/tasks/ directory.


desc ‘Deletes all files that end with tilde (~)’
task ’tilde’ do
files = []
Dir.glob(’**/*~’).each do |file|
File.delete(file)
files << file
end
puts “Deleted the following files: #{files.join(’, ‘)}”
end

To run the task, simply run the following rake tasks from your shell:

rake tilde

Update: See Dominic’s comment. Rake already includes a task to clean-up files. Just need to include ‘rake/clean’. Thanks Dominic.

Tip 2: Small Erb Tip

Did you ever need to display <% or %> in an erb template but didn’t know how to do it? I’ve been there!

It’s quite easy actually, all you have to do is use <%% and %%> instead and the erb templating engine will replace them with the appropriate <% and %>.

Tip 3: Detect Cross-Script Scripting (XSS) Attacks ‘Holes’

If you do not know about XSS attacks, panic and go read this chapter of the Rails manual to learn about them.

Rails provide the h() helper method for HTML meta-character conversion in views. It’s important to use it whenever you are inserting dynamic data in your erb templates.

Sometimes, I want to double check that I’ve been using the h() helper methods everywhere so I want a list of everywhere I’ve used <%= in my views. I use the following command to scan through all the <%= where I’m missing the helper method:

grep -R '<%=' app/views/* | grep -v '<%=h' | grep -v '.svn' | more

Rather than typing that command everytime, I simply created an alias for it by saving the following in my .bash_aliases file:

alias xss_erb_scan="grep -R '<%=' app/views/* | grep -v '<%=h' | grep -v '.svn' | more"

Tip 4: gEdit on Rails

My laptop runs Ubuntu so I use gedit for doing Rails development. gedit is highly configurable and you can turn it into a bad-ass Rails-IDE with a few tweaks.

First follow the steps on this tutorial. This will make your gedit environment pretty much ready for rails development.

Then, you can add the ability for gedit to execute Ruby code that you have in your currently open document by just using a keyboard shortcut. To do this, first install the ‘External Tools’ plugin. Go to ‘Edit’, then ‘Preferences’, and select the ‘Plugins’ tab. Find and select the ‘External Tool’ plugin and click on ‘Configure this plugin’. The following window should popup.

Click on the ‘New’ button and create an ‘Execute Ruby’ tool by filling in the information as shown below:

That’s it. You can close the window and test by writing some ruby code in a new document and pressing F5. The code will execute and the output will be shown at the bottom of the editor.

Tip 5: Explore Other Ruby Web Frameworks

My last tip is to explore other ruby web frameworks. There are a lot of other web frameworks written in Ruby and you can learn a lot by just exploring them. Even if you do not plan to use them for a production site, try using them for a small project, look inside their codebase and try to understand the code. Since Rails is a more mature and more complex framework, it can be scary to look inside the Rails code but the same can’t be said for some of the newer, lighter frameworks out there. Furthermore, exploring these other frameworks can give you new ideas when working on Rails projects. So just like the pragmatic programmers advocate learning one new language a year, I recommend learning a few web frameworks in that language during that year to expand your knowledge of the language and avoid tunnel vision. So go start exploring Merb, Ramaze, Camping, Sinatra, etc… Check here for a full list of Ruby web frameworks.

I hope you will find some of these tips useful. I look forward to read the tips submitted by the other railscast readers.




becamp slides - Ramaze

3 05 2008

I am in Charlottesville attending becamp and I just talked about Ramaze, a lightweight web application framework written in Ruby.

My slides are below. They are also on scribd.

We had a very good group here and some interesting talks. I particularly enjoyed the talk on High Performance MySQL by Baron Schwartz. Ahson started a good discussion on Web 3.0. The other sessions I attended were on ‘Javascript Design Patterns’, ‘High Availibility Linux’, and ‘Google App Engine.’




Follow-up on Ruby On Java Presentation

25 08 2007

Earlier this month, at Barcamp DC, I talked about using Ruby with Java using JRuby, JSR-223, and the Bean Scripting Framework.

Today, I found this great blog post that describes using the BSF to call Ruby’s ActiveRecord from Java.




Book Review: Beyond Java

22 08 2007

I just finished reading Beyond Java – A glimpse at the future of programming languages by Bruce Tate and I really enjoyed the book. I can’t wait to pass it on to friends and co-workers that are Java developers. I think every Java developer should read it.

Unfortunately, it is the kind of book that will be affected by time as the content will not be relevant anymore a few years from now. As a matter of fact, some of the content is already somewhat outdated but the main ideas are still relevant. So if you haven’t read it yet, go get it now and read it. It’s a small book and a quick read.

Bruce Tate believes that Java development has become too complex and that Java lacks some of the features that are desirable in a modern programming language. In his opinion which I share, Java is too verbose: “Even with seasoned developers, it takes a surprising amount of code to get even simple applications off the ground.” (p. 4). With dynamic languages like Ruby or Python, you can see incredible power and productivity very quickly. In addition, Java does not support metaprogramming or continuations natively.

In Chapter 2, entitled ‘The Perfect Storm’, the author does a great job of describing the environment in which Java emerged to become the dominant programming language. For anyone in need of a quick recap of the recent history of programming languages, this chapter is a great read. The next Chapter is a eulogy of Java where the author describes what Java does right and the features and circumstances that makes Java so successful. Bruce Tate then exposes the limits of Java and offers a comprehensive list of rules that the next successful language will need to follow to become the next Java.

Chapter 6 is a quick overview of Ruby that demonstrates that Ruby possesses a lot of the qualities needed to cross the chasm and become the next big programming language, including having a killer application in Rails (which he reviews in Chapter 7). Finally, the next chapter takes a look at continuation servers and uses the Seaside framework written in Smalltalk as an example. To me, this chapter was probably the most interesting in the book. My only introduction to continuation servers before this was when Chad Fowler briefly mentioned them at the Advanced Ruby Studio that I attended last month. It is a fascinating topic and I will definitely do some digging to learn more about them. Maybe I’ll give Seaside a quick try.

The author also mentions a few major (Python, Groovy, .NET) and minor (PHP, Smalltalk, Lisp, Perl) contenders. He thinks that “Perl is too loose and too messy, PHP is too close to the HTML, Lisp is not accessible, and Smalltalk wasn’t Java” (p. 171).

In conclusion, the goal of the book is to warn Java developers that Java is moving away from its base (it’s getting too difficult to solve simple problems in Java) and showing signs of wear. In the meantime, interesting innovations are appearing in other languages so it is time for Java developers to start paying attention to the world outside of Java.




Barcamp DC - Ruby on Java

15 08 2007

Barcamp DC was great. It’s good to see the DC Tech community get together for events like these.

The first session I attended was an introduction to Ruby on Rails given by Kevin Lawver. I thought it was very cool that Kevin brought his son with him. He seemed to really enjoy the un-conference.

After that, I sat through a couple of good sessions on User Experience and Design Challenges. They were both very interesting discussions. The Design Challenges discussion was initiated and moderated by the folks at Viget. I really enjoyed this one from a non-designer perspective. It seems like a lot of the challenges they face are very similar to the ones a software developer faces such as communication with the customer.

Scott Mendenhall squeezed two talks into one session: Open Source CMS and Ajax Network Latency. The first one was a survey of Open Source Content Management Systems. There are a lot of them out there and a big consulting industry around them. Scott claims that some consultants charge as much as $50,000 to recommend a CMS. The Ajax Network Latency talk was of interest to me because I have been dealing with that issue at work with the Verizon FiOS project.

For the rest of the day I attended a session on the Mobile Web, a Ruby Crash Course, and a Rails open session.

When it was my time to talk, I presented on Ruby and Java cooperation. My slides are here or below:

Overall, I really enjoyed the day and I look forward to the next BarcampDC.




Rails :include Gotcha

1 07 2007

If you are using the :include option of the find function in Active Record, there is a big gotcha: you have to disambiguate all column names used in other parameters to ‘find’ (prefix each with the name of the table that contains it).

For example, the following will give you an error:

Post.find(:all, :include => [:user, :comments], :order => “created_at DESC”)

The error that you get is the following: Column ‘created_at’ in order clause is ambiguous
The fix is really easy:

Post.find(:all, :include => [:user, :comments], :order => “post.created_at DESC”)

Note that I changes created_at to post.created_at.
I would have saved myself some debugging time had I known that so I just wanted to share.




NovaRUG Meeting: Chad Fowler

23 02 2007

Last night, I attended the Nova Ruby User Group (NovaRug) meeting in Reston. Chad Fowler was the speaker for this month’s meeting and he gave a talk on writing clean rails code. The title of the presentation was ‘Quick & Clean’. Chad explained how there are usually two kind of solutions when designing a software system: the slow and clean solution or the quick and dirty solution. He believes however that with Ruby on Rails, it is possible to achieve a Quick & Clean solution. He said he first heard about that train of thought from Martin Fowler at RubyConf.

The problem is that a lot of times, Rails is used to produce Quick & Dirty coding. While working as a consultant, he claims to see a lot of dirty rails code. So while ‘quick and clean’ rails is possible, it is not probable. Thus, his talk was a grab bag of strategies and best practices to write clean rails code. Chad jumped from topic to topic and kept the crowd entertained for about an hour and a half before opening the floor for questions.

Here is some of the stuff he pulled from his grab bag:

  • Ruby on Rails makes it easy to build Leaky Abstractions. To avoid these, he thinks the best solution is to learn and master Ruby so that you at least understand what goes on below rails. This will help you write code that is more clean, faster, and more efficient.
  • Ruby gives you a lot of rope. Compared to Java & C++, it doesn’t tie you into a set of rules and lets you do pretty much anything you want. This is great if you are a good programmer but it also makes it prone to making big mistakes. He said that Java was designed with the mindset that it will be used by dumb monkeys. Therefore, the designers put mechanisms in place to avoid the monkeys from making stupid mistakes. In the process, there are more constraints on the things you can do. On the other hand, Ruby was designed for smart programmers. It lets you do a lot of things. The problem is when monkeys try to use it they can make cataclysmic mistakes since nothings stops them from doing so.
  • CRUD stands for Create, Read, Update, Delete. Chad said that as a Rails developer, you have to force yourself to CRUD. When designing an application, force yourself to architecture it in a way that the only operations needed on a model is Create, Read, Update, & Delete. This will make you write cleaner code. He also mentioned that the Rails core team is going to enforce this in Rails 2.0.
  • Chad advised against putting SQL in controllers. Move your SQL to the models. Also, a controller action should never have more than 5 lines. Force yourself to follow that convention and your code will be much cleaner.
  • Dry up your controllers with before_filters. It helps eliminates lines of code.
  • Sometimes you just have to make your own language. He quoted ‘Good APIs are languages’. For some applications, you might need to develop an API with functions handling stuff you do often.
  • Do not put code in your views. Hide the ugly things where you do not want to have to look at them. Put them in helpers or in the models. There is always more opportunities to clean up your views.
  • Check out simply_helpful plugin. He claims it can help you a lot and will be included in Rails 2.0.
  • He recommended to read the book: ‘Leading The Revolution’ from by Gary Hamel. It’s a business book that he claims will help you in every aspect of life.
  • Chad briefly talked about the effect of globalization on software developers in the US. One interesting thing he said is that India is now outsourcing developers to China because the cost per hour per head for a developer in China is much lower than in India. Also, China is now mandating English at school.
  • A few of other things that was mentioned that you might want to google: RJS, with_scope, Amrita, update_page, Naked Objects, Hobo.
  • To finish, Chad stated that to be a good Rails developer, you need to become an expert at Ruby. It will help you see through the leaky abstractions and write cleaner and more efficient code. I was very glad to hear that. On my path to learn Ruby on Rails, I had decided first learn Ruby before I start learning Rails. So it made me realize that I might have started the right way.

    I was very glad to attend this NovaRug meeting and I look forward to
    the next one. If you live in the Northern Virginia area, I would
    highly recommend coming to the meeting if they keep being this
    interesting.