The most hilarious Rails post ever

Posted by admin 27/09/2007 at 08h52

I was browsing around DZone and found a post by Alex Bunardzic satirizing the now common “Why I switched from Rails to WHATEVER” posts that have been flying around the net. His language of choice: Assembler. Take a read and dont blame me if you fall out of your chair.

PS You must be a nerd to understand :)


Quick Zebra Striping in Rails

Posted by admin 12/08/2007 at 08h57

Striping table rows is usually a necessity when making accessible web pages. This can be a tedious task. Through the ages (and by ages I mean the last 10 years or so) there have been many ways to do this in many dynamic languages. Everything from taking the modulo of the index when iterating through the set, to flipping a counter back and forth.

Well, if you’re programming in rails, you get a much easier way to do it via the cycle method. Let me show you how easy it is:

  <% @objects.each do |obj| %>
  <tr class="<%= cycle("even", "odd") %>">
    <td><%= %></td>
    <td><%= obj.title %></td>
  <% end %>

Simplicity itself. Now as you loop through the set, it will cycle the class name of the row between “even” and “odd”. Now all you need to do is set CSS values for those classes and your done.

Here is a quick example of a CSS class for odd:


Gotta love rails.


Rescuing Ruby

Posted by admin 11/08/2007 at 19h07

Now, before anyone goes crazy, this article has nothing to do with saving ruby from something, i just couldnt think of a better title. We will be talking about rescue and some cool tricks that can be done with it.

As most of you vets know, every thing in Ruby is an object. What most noobs dont realize is how powerful that can be and how concise your code can become. Of course, the flip side of that problem is what i call, newbie-come-expert. It’s basically the stage in a noob’s study of a language where they think they know enough to write really cool software. What actually happens is they end up with code like this: {|e| [, e.title]}.sort {|a, b| a.last <=> b.last}.map {|e| e.join(" ")}.join("\n")


Dont worry noobs, everyone does it. I’m still trying to undo it from some of my older code.

Anyway, my point is, sometimes Ruby’s dynamicism (say that 3 times fast) can lead to messy code so use this tip wisely.

On to the actual tip.

So, like I said before, EVERYTHING in Ruby is an object, even the remains of a rescue clause or an inline rescue which is what we will be playing with here.

How many of you have done this:

@person = Person.find(some_id)

only to get the following error:

ActiveRecord::RecordNotFound: Couldn't find Person with ID=22

It’s pretty annoying, mainly because this type of thing could easily happen in a live app. A user goes to find something that isnt there. One way around it is to have a rescue at the end of the method, but what if you have multiple finds that could throw errors? What if you still need to be able to proceed with whatever you are doing, even if the object isnt found?

This is where inline @rescue@’s can help.

Now you can pull all of your finds together and end them with a rescue.

Let’s say you had the following code:

@person = Person.find(params[:id])
@employee = Employee.find(params[:employee_id])

Now, if either of these finds fail, you will get an error. Instead of rescuing the entire method, you can resuce each statement and make the return value nil and check for nil like you normally would.

New code:

@person = Person.find(params[:id]) rescue nil
@employee = Employee.find(params[:employee_id]) rescue nil

Now when you cant find the ID, it will rescue and just set the variables to nil and move on.

You can also set the rescues to another default datatype instead of nil.

Now, you may be saying, “Wait, why would a user need to enter an id”. Well, one example is an order id, or a tracking number. Anyway, I have run across this a couple of times and thought i’d write something about it.

until next time.


Rails Plugin - Jake's Rails Toolbox

Posted by admin 10/07/2007 at 13h56

hello all,

Ive recreated my old plugin and updated with some new features.

I created this plugin as a hodgepodge of different methods/hacks that i have found useful over the course of developing Rails Apps. I packaged it up as one plugin because most of the methods have nothing to do with each other, but i find them are very useful going from project to project.

Lets talk about them:

ActiveRecord Hacks:

1. Dynamic “nice_date”

Basically, i got tired of typing object.created_at.strftime(“%m-%d-%Y”) so i came up with the following method_missing hack for any Time attribute in an ActiveRecord object. Just prepend “nice_” in front of any Datetime attribute and you will get a nicely formatted date string. Plus some other goodies :)


# => Mon Dec 04 12:36:55 CST 2006
# => "12-04-2006"  (mm-dd-YYYY)
# => "04-12-2006"  (dd-mm-YYYY)

plus, for you guys (and gals) that like using slashes instead of dashes:
# => "12/04/2006"  (mm/dd/YYYY)
# => "04/12/2006"  (dd/mm/YYYY)

and finally:
# => "Mon, 04 Dec 2006 12:36:55 -0600"  (rfc822)

The attribute must be an instance of Time or a NoMethodError will be thrown

2. Dynamic SEO formatting.

Any method that returns a string can use this dynamic method. This method will create an SEO friendly string out of the attribute chosen (for use mainly in URLS). It will append the objects id (not the object_id, but the id key from the database) so that you can use params[:id] and not have to create new routes.


# => 1
object.title = " Rails is freaking awesome, didn't you know that?  " 
puts object.seo_title         
# => "1-rails-is-freaking-awesome-didnt-you-know-that" 

3. nice_name

This one is pretty simple. I found myself adding this same method to alot of my applications. Basically it looks for an attribute called “first_name” and one called “last_name” and combines them together with a space in between.


object.first_name    = "jake" 
object.last_name     = "varghese" 
# => "jake varghese" 

If the method doesn’t have EITHER first_name or last_name, then a NoMethodError
will be thrown. It must have both attributes

4. create/new from XML

Create an ActiveRecord Object from XML. This method relies on the basics of AR’s current to_xml method (basically, it must be formatted the same).The differences between new_from_xml and create_from_xml are the same as the differences between and AR.create

If your XML string contains multiple records, it will parse out each record and create an object. The “multiple record” call returns an array like find(:all)


person = Person.new_from_xml(xml_string)
# => #<Project:0x2430758 @attributes={"prototype_url"=>nil, "company"=>"some value", 
"order_id"=>45564, "phone_number"=>555544455, "created_at"=>nil, 
"email_address"=>}, @new_record=true>

String Hacks:

1. SEO friendly.

This method is used in the AR seo hack. It takes a string and makes it seo friendly.


c.title = " Rails is freaking awesome, didn’t you know that? "
# => “rails-is-freaking-awesome-didnt-you-know-that”

Float Hacks:

1. to_s override.

I really hate using sprintf, mainly because i always have to go online and look up the syntax. I figured i make that a little easier. Now you can print floats with different precision as easily as:


4.123456.to_s(1) # => “4.1”
4.123456.to_s(3) # => “4.12”
4.123456.to_s(3) # => “4.123”
4.123456.to_s(4) # => “4.1235” (Note the auto rounding from 4.123456)
4.123456.to_s # => “4.123456”

Hash Hacks:

1. Method Missing hack to allow for easy hash referencing.

I can never remember whether the Hash i am playing with has symbols for keys or strings. I also dont like typing the brackets (not all text editors have the cool “auto close brace” feature). That’s why i came up with this method missing hack. Instead of explaining what it does, I’ll just show you.


hsh =  {"project"=>
#=>  {"prototype_url"=>nil, "designer_id"=>2, "finished_at"=>nil, 
"phone_number"=>"512225555", "website"=>"", 

#=> nil
#=> 2
#=> test

So instead of hsh[“project”] you can just write hsh.project

and that’s it. If you want to try it yourself, just run

script/plugin install 

You can also checkout the latest rev via SVN at:

svn checkout vendor/plugins 

New Rails Plugin - Acts As Noteable

Posted by admin 10/06/2007 at 13h51

So I was at work and I needed to add notes to multiple models in the same project (before i only had to worry about one model with notes, so it was pretty straightforward). So i bit down and knocked out this little plugin.

I borrowed heavily from Acts As Rateable by Juixe


Run the following command:

script/plugin install

The install will try and copy some scripts over, this works sometimes. If you get a rake error do the following:

  1. cd vendor/plugins/acts_as_noteable
  2. rake update_scripts

Create a new rails migration:

script/generate migration add_notes_to_project

and add the following self.up and self.down methods

    def self.up
        create_table "notes", :force =&gt; true do |t|
            t.column "from", :string, :limit =&gt; 50, :default =&gt; "" 
            t.column "body", :text, :default =&gt; "" 
            t.column "created_at", :datetime, :null =&gt; false 
            t.column "noteable_id", :integer, :default =&gt; 0, :null =&gt; false 
            t.column "noteable_type", :string, :limit =&gt; 15, :default =&gt; "", :null =&gt; false 

    def self.down
        drop_table :notes 

(one day i’ll add a migration script to the plugin to automatically add this :) )

After that run “rake migrate” to create the table.

Now all you need to do is call acts_as_noteable in your model:

class Model &lt; ActiveRecord::Base

Now your model is notable, but that’s not all.

For only 19.95 you get a Helper method to help you create a nice form. Ok, so i am not actually charging, but whatever.

Here’s how the helper works.

In the view you want to display notes in put the following:

&lt;%= display_notes(object) %&gt;

This will create a div filled with the note entries for the object and a AJAX form to add new notes to the object as well as delete notes from the object. The add and delete methods are stored in the notes_controller.rb that gets copied over into your app/controllers directory.

The full implementation for this method is:

&lt;%= display_notes(obj, partial_name = "notes/note", controller_name = "notes") %&gt;

I added the partial name and controller name in case you have multiple controllers in different folders, this way you can display notes for objects whose controllers are buried deep in a folder.

Example: I have an “admin” folder for all the backend stuff and I needed a way to reference the notes controller from different places, otherwise RAILS will assume you are trying to reference a controller from the current folder your in.

After you have called display_notes, your done.

Note** This plugin has not been tested with Rails 2.0 yet