Rails Code Snippet Starter Kit

Published  October 11th, 2010

Sometimes one piece of code in a language doesn't translate verbatim to another. Sometimes 5 lines of code can be written in 1. That is what this post is about - the snippets of code you lean on during the early stages of your Rails learning.

1. Avoiding use of if/else/unless when unnecessary

Ever heard of a ternary operator? No? It seems like one of those names that no one remembers and every one just creates their own name for it. There's a good chance you've seen one before because they're quite handy in the right situation. Here's what they look like:

2. Use the tools Rails blessed you with

Rails provides a lot of cool, built-in functionality with accessing your models. Before you re-invent the wheel, make sure Rails doesn't have something in place for you to use. For me, I wrote a lot of duplicate code in the beginning (and still do unfortunately) because I just didn't know all the tools at my disposal. So here's a helpful one, the Rails 'find_by' method. Instead of writing out an SQL-like statement for your model, use the 'find_by' method like this:

3. Knowing your 'self'

Pretty cheesy heading for this one. Sorry, I couldn't resist myself. Using 'self' can be confusing at first, like when to use 'this' in JavaScript, but it's something you need to get under your belt and once you do it becomes common practice. Here is a simple example:

4. How to use variables in database look-ups

This is one that caused me to go back and re-write a lot of my code. Not only is it good practice, but there are serious security concerns around using variables in database queries. If someone knows their way around escaping values, you run into some nasty potential SQL injection problems. This might not be news to you, but if you've never been told, here's the right way:

Hopefully some of these are helpful. I plan on adding posts similar to this as I learn more.