href_to_params

Every now and then I find myself in need of the ability to take a string like “http://www.estately.com/p/WA_Seattle” and figure out the params hash that it would generate - the method to do that in rails isn’t immediately obvious, but after a little digging, I’m happy to say it isn’t too hard.

I admit, I generally treat Routing as a black box: type a url in the browser and I get a params hash - works for me. I thought I was in for some serious digging to figure this one out, but it turns out it already exists, but only for testing under the name assert_recognizes. Adding the ability to recognize query strings, I came up with the following:

This was with about 30 minutes of research, so there very well could be a better way, but this works well for me. If anyone knows a cleaner method I’d love to hear about it.

Update:
I missed it during development, all the tests passed, but there’s something missing from above:

TestRequest can’t be auto-loaded by rails because it’s in a file called test_process.rb, and of course this wasn’t caught with tests as it is already loaded in the testing environment, guess TDD can’t save you from yourself.

An Ode to the cool American Nerd: Jamis Buck

Pretty Boys

Jamis

Take a look at the pictures in this post. Who’s the real nerd? Jamis Buck or the pretty boys posing in the hallway?

We all know the answer. Those guys didn’t play D&D after the age of 13. It’s Jamis, one of the clearest writers, one of the best OSS contributors and one of the nicest people in the rails community. Call me old fashioned, but I don’t trust coders who look like that.

Mechanical Turk Gem

Amazon’s mechanical turk gem 0.90 was released a couple of days ago (download here). We aren’t using Mechanical Turk yet, bu I have a myriad of things I’d like to try it on.

Mechanical Turk is brilliant, but it seems a unnecessarily complicated on the developer side. The documentation is thorough, but I couldn’t find a good step by step walk through for posting ‘hits’ and getting results. The sample “get your balance” code doesn’t really cut it for this mechanical n00b. This form is nice for one-offs. The docs don’t hold a light to the Google Maps api docs.

I’ll be sure to post a rudimentary how-to when we at last get around to utilizing The Turk.

Script/generate and add to svn at the same time

I’m probably the last to know how to add files to svn as you are generating them. Add -c to your command:

script/generate migration likeability_to_homes -c

And you don’t have to svn add your way to carpel tunnel.

If you aren’t using Firebug yet, you should be

We’ve decided that if it cost money, we would pay for Firebug.

Since I installed it, I’ve found myself tweaking a lot of designs in Firebug. It’s especially helpful if you want to see what a page would look like with our without specific styles or if you can’t figure out why certain elements are getting styled the way they are. Sometimes, when I want to add an element to ShackPrices, I find the element I want to add it to and start editing the html in Firebug. It’s incredible how much more productive I can be with instant feedback (4px padding? no 5px looks better). When I’m done, I just cut and paste the html into Vim.

Additionally, for you ajax nerds, Firebug shows you the contents and type of every ajax call and the contents of the response, so you don’t have to spend as much time looking at your logs.

If you aren’t using it already, give it a try.

The Null Object Pattern for Users

The Null Object Pattern certainly isn’t a new idea, but it’s simple and can really help clean up some code, so I thought I’d share an example.

Background
Our login system is based off of acts_as_authenticated, but very few of our pages require a user to be logged in. We want to find out about the current user, but first we need to make sure they are logged in, otherwise current_user will return nil and you’ll end up with a NoMethodError. So we end up with a lot of code that looks like this:

Not too bad, but this pattern shows up all the time in our code.

A Solution
Null Object to the rescue! The idea is dead simple: instead of returning nil if the user isn’t logged in, just return a instance of a new class - NilUser.

Now we just update current_user to return a NilUser if the user isn’t logged in:

Now all of our conditionals are shortened to a single condition, much nicer.

Final Words
If you try something along these lines, just remember to add corresponding methods to your new class for each public method of the class you are potentially replacing. If you felt like living dangerously you could even add a method_missing to your nil class that returned nil on any undefined methods and only define methods where you wanted a different return value - but this could easily turn into a debugging nightmare.

Also make sure to update any code where you depended the returned object being nil - for example:

will be broken. You might even need to add another method to your Null Object class, something like:

In our case we can use logged_in? if all we want to know is whether a user is logged in or not.

That’s all there is to it! While not something you’d want to use all the time, when used appropriately it can help cut a lot of repeated code in your conditionals and improve the code’s readability.

Next Post: A little meta-programming to simplify the nil class definition

Rad Rad Rad Gems and Plugins for rails

Things have come a long way since the first project I developed on rails. Starting out I wanted to keep things simple but now I can’t get enough of the time saving complexity that many great gems and plugins bring!

So here they are, in no particular order at all, a few of the recent tips, tricks, plugins and gems I’ve found to be rad rad rad.

ZenTest
If you’re not testing you’re wasting valuable time. If you’re testing but not using ZenTest you’re still wasting valuable time. In particular, autotest (a part of the ZenTest gem) is a brilliantly simple approach to reducing — as much as I’ve ever seen done — the gap between test and code. You run it and it tests your code whenever and as soon as you change it. Rad rad rad.

Piston
You’ve got plugins or you’re working on the edge and you want that 3rd party code to be up-to-date, right? How annoying is it to re-install that stuff and re-import it into your source tree? Piston acts as an interface between your source tree and the source trees of your 3rd party applications and plugins. piston update and you’re source suddenly has an up-to-date copy, committed and ready to go.

ferret
Hello full text search! This port of the popular, well-designed Java search system Lucene, is an easy way to effectively index the plain text in your models. I find it to be a better fit for most of my projects than MYSQL full text indexing because it exists separately from the database and is explicitly designed for text search.

capistrano
If you’re not using this deployment management tool you’re wasting precious time! It’s simple to setup and easy to use. Let’s see, let me go to my rails root. I’ll enter cap deploy. 1, 2, 3, 4, 5 seconds later and I have the latest version of my source installed, my application servers have been reset, the database migrated, AND I’ve got a complete copy of the last deploy to rollback too if need be. Oh and it resets my backgroundrb (see below) processes plus a bunch of other custom stuff I wrote. Rad Rad Rad.

backgroundrb
In the Java world this would be called Quartz. In the ruby world its just as indispensable. Perhaps not when you’re starting out, but pretty early on you can be sure you’ll need to run, on an automated basis, various scripts. I use it to manage the sending of emails so that I don’t tie up my mongrel application processes. I also use it to do database and session cleanup.

RedHill Consulting Plugins, et al
These guys offer a series of plugins so simple and useful they feel like they ought to have been a part of rails itself. foreign_key_migrations is a plugin that automagically creates indexes in your database based on your database schema. A users table which references a article_id will automatically get an foreign key index to the articles table. Rad rad rad. (This can create some hassle with your test fixtures though, since you won’t be able to insert data with bad references.)

Exception Notification
This plugin is a life saver! And pretty annoying too! It makes it easy to get an email detailing what happened when something goes wrong with your rails app.

Routing Navigator
This handy plugin can really help with the transition from your old rails app to your new RESTful application by displaying information about all the routes and named route methods being generated by your routes.rb

Simply Helpful
Written by DHH himself, this set of helpers and methods simplifies a lot of common tasks. polymorphic_url(object) generates the correct URL for any model which has coverage in your routes.rb. dom_id(object) will create a class + id based identifier which you can reference in your RJS scripts and HTML to ensure everything gets wired up correctly. Handy!

Paginating Find
I’ve just started using this one but it looks great. Instead of using this weird extra pagination method, paginating find adds a few simple options to the built in find command to more efficiently allow you to select out pages of models.

File Column
Though not updated in a while, this plugin makes it super easy to add files to model objects. In particular, it handles images very well and has great integration with rmagick to automatically do things like image resizing and version management.

Validates Url
A little something I wrote, this guy does simple validation on model fields to check that they have a certain protocol and are correctly formed server/path strings.



My name is Peter T. Brown. I am a partner at Waggle Laboratories, LLC which develops lightweight social applications for business and pleasure. Our latest and greatest is RealityAllStarz where you earn points for doing unusual and interesting things!

Business geeks on their true passion: code

Normally I’d suggest starting a blog about code by just jumping in - it ain’t a blog about talking, right? But I’ll disregard my own advice and give you a little background first.

Doug and I started ShackPrices.com a little over a year ago and settled on Ruby on Rails a couple of months later. We learned Ruby and Rails via the traditional route - purusing the ten million “do X in 15 minutes with rails” stories on the web, reading through the Pragmatic Programmers Rails book and finally turning to the API and some solid rails blogs including:

err.the_blog
Nuby on Rails
Ruby Inside
has many through
(and many more)

We found that blog posts are often the best and most effective documents for learning more about Ruby and about Rails.

Every so often we create our own solution that so impresses us that we want to share it with the community, but we don’t have the time (or the abundance of genius) to post often enough to make a stand alone blog. So we’re putting together a blog where we can post our insights along with insights from a bunch of other rails-driven startup founder / coders. Hence “Startups on Rails.”

We’ll be introducing those other contributors in the coming few weeks.

startups.each { |startup| startup.code.inspect }