Find objects in IRB directly from browser URLs
A long time ago, I tired of going into the irb/console and finding objects/models using the traditional ActiveRecord command Person.find(15) and now I’m sitting pretty: I can paste in URLs to fetch objects.
# No more of this: => Person.find(15) # instead: => people/15
people/15 is something you’ll copy+paste directly from your browser: http://localhost:3000/people/15
Of course, the url is based on your routing + controllers, so the assumption here is that your routes/controllers map to your active record models. That is, your app is smothered in RESTful love and cuddles.
Not following this? Here’s a video:
How to make this work at home
Copy and paste the following into your .irbrc file:
Thanks goes to…
The some original code for this comes via Mike Clark, who had the idea for syntax activity(6). This was good.
I previously had another idea to support the syntax 6.to_activity using the RubyGem to_activerecord. I still like the id.to_class_name structure of this and still use it.
But if I have a perfectly nice looking url sitting in front of me, I can now paste the class_name/id part into irb and I’m off and running.
Happy New Year.
Trackbacks
Use this link to trackback from your own site.

I like it.
I like it a lot.
So how about nested routes? … Just kidding
or am I?
Ooh, I forgot the hook! You’ll need to add the following to the bottom of your .irbrc file:
IRB.conf[:IRB_RC] = Proc.new { define_model_find_shortcuts }@mislav [via] - ok, figured out how to support has_many nested_routes, e.g.
people/123/addressesSee the pastie
NOTE: This assumes there are models Person and Address, and
Person.has_many :addressesNifty.
@drnic Hey Gem master, what about packaging all of that in a nice gem a la wirble?
RE caboose chat:
http://pastie.caboo.se/133959
You’ve now got no excuse to add in support for all restless urls (as far as logical) and package it up into a gem. DO IT NOW
http://pastie.caboo.se/133977
This handles url of the type: /users/david
Now only need to figure out /users/david-myopenid-com and we’re all set.
@saimon [via] - Very nice work
I added the following when clause to the #evaluate method to support development urls (e.g. http://localhost:3000...)
when /^(http|https):\/\/[a-z.]+:[0-9]+(([0-9]{1,5})?\/.*)?$/ix original_evaluate($2.gsub(/(^\/)/,”), line_no)@Dr Nic [via] - Cool stuff…Looking good…
While this is a neat little trick, I really don’t like the tight coupling between the way to access the resource at HTTP level and database level.
Matt Aimonetti noted that outside of script/console, there was an error with pluralize missing from String class. #pluralize is an active_scaffold contribution.
I realise I have the following at the top of my .irbrc file:
That is, if you’re in irb, and /config/environemtn isn’t loaded, then explicitly load active_support.