"HowTo" Posts
Posted in HowTo, Ruby on Rails | 1 comment 
James
One of our current projects at Highgroove sends a lot of email to its users. It essentially walks them through a process and emails them at each step. All of those messages include URL's to visit the relevant page in the application for that step. Since we've emailed them the URL's we don't want them to have to login every time they click one.
To get around that I modified the application to accept URL's like the following:
http://domain.com/login/TOKEN/ANY/SITE/URL
These URL's log the user in using their security TOKEN and then redirect them to /ANY/SITE/URL. This setup allows me to easily forward a user to any URL on the site which is great when writing all of these emails.
The code is easy enough too. I imagine many of us have a sessions controller that looks something like:
class SessionController < ApplicationController
def create
if user = User.authenticate(params[:email], params[:pass])
# log user in...
else
# login error message...
end
end
# ...
end
First, I just added some support for the token based login with redirect to that:
class SessionController < ApplicationController
def create
if params[:token] and (user = User.find_by_token(params[:token]))
# log user in...
if params[:path].is_a? Array
redirect_to "/#{params[:path].join('/')}"
else
redirect_to home_path # or whatever default page you want
end
elsif user = User.authenticate(params[:email], params[:pass])
# log user in...
else
# login error message...
end
end
# ...
end
The magic redirect_to() call in that new code uses a not-often-seen feature of Rails's routing. You can specify that Rails collect any number of trailing URL bits into an Array much like Ruby can do for method parameters. Here's the route definition I am using to get users to the code above:
# a custom login route with forwarding
map.connect "login/:token/*path", :controller => "session",
:action => "create"
The *path is the magic slurping parameter syntax, again just like arguments to a Ruby method. Rails will collect each piece of the remaining URL into an Array called path, so just remember that you need to rejoin the elements to make them a real URL again.
Posted in HowTo, Ruby on Rails | no comments 
Derek
Sometimes our Ruby on Rails apps work perfectly with test data, but when they go to production, errors creep in. Debugging errors on a production server is a pain and a bit dangerous.
Here’s what we do to quickly and safely debug issues on our production servers:
1. Add the following capistrano task to create an SQL dump of your data. If it’s a large database, it may be worthwhile to compress the SQL dump as well.
desc "Exports the production db to the home directory of user"
task :db_dump, :roles => [:app, :db] do
run("mysqldump -u #{database_username} --password=#{database_password} #{application}_production > production.sql")
end
2. Create the following rake tasks to grab database dump and import the data locally.
namespace :db do
desc 'Grab a dump of the production database on the server and places it in db/production.sql.'
task :get_production do
`cap db_dump`
`scp DEPLOY_USER@SERVER_NAME.slingshothosting.com:production.sql #{RAILS_ROOT}/db/production.sql`
end
desc 'Imports the database dump of file db/production.sql into development.'
task :import do
`mysql -u root app_name_development < db/production.sql`
end
desc 'Grabs a dump of the production database from the server and imports the data into the local development database.'
task :get_import => [ :get_production, :import ]
end
3. Install the Firefox plugin Server Switcher to make it easy to switch between the production and local server in your web browser.
4. Disable mail in your development box – it’s not a good feeling when you realize you’ve emailed several thousand users while testing out a newsletter script.
config.action_mailer.delivery_method = :test
Posted in HowTo, Ruby on Rails | no comments 
James
I just finshed fixing file uploads in a HighGroove application to work with any size file. I uploaded a 14 byte file to make sure I had things right. This has a few gotchas in Rails, so I thought I would share the recipe for success.
Read more... 
Posted in What We Wrote, HowTo | 2 comments 
James
Just wanted to make sure HighGroove customers and fans are the first to know, my new book is official:
James’s Book on TextMate
If you’re living under a rock, TextMate is the wildly popular text editor for Mac OS X shown off in most Rails screencasts.
It even won the covetted Apple Design Award for Best Developer Tool just a few weeks back.
I’ve been heavily involved with TextMate development for some time now and am excited about the opportunity to show you how to really get the most out of it. The book will cover beginning to advanced editing techniques, built-in automations and how to create your own, even how to teach TextMate new languages. I promise, there’s something for everyone in here.
Some time ago I read a “10 Best Things You Can Do as a Programmer” list and one of the points on that list was: Learn one text editor very well and use it for everything you can. I believe that’s great advice and TextMate was my pick. I’m now ready to pass that knowledge on to all of you!
You’ll be seeing even more news about this book very soon now. (Weeks, not months!) Stay tuned…
Posted in Salesforce, HowTo, Ruby on Rails | 1 comment 
Derek
Salesforce, the large Customer Relationship Management tool, and Ruby on Rails, the elegant web development framework, seem like an awkward pair. About as awkward as dipping a Wendy’s french fry in a frosty.
Salesforce is large, often times confusing, and is a tool built for handling lots of different jobs. Rails is lean, elegant, and designed specifically for making web development easier. While Salesforce and Rails are dramatically different, they actually work very well together (much like a Wendy’s french fry dipped in a frosty – trust me).
This unlikely pairing is sparked by ActiveSalesforce, a Ruby on Rails connection adapter to Salesforce-managed data. This Ruby Gem makes working with Salesforce data about as easy as the Rails-MySQL combination.
Highgroove Studios is working on a Salesforce-Rails application, and one of the things we have to do is synchronize a local MySQL database with Salesforce. This is needed because the connection to Salesforce is slower than when working with a local database, and several parts of the application are time-sensitive.
Here’s a look at how we designed the application to synchronize data between the local database and Salesforce.
Read more... 
Posted in HowTo, Ruby on Rails
Derek
Metaprogramming is your secret identical twin that likes doing all of the things you don’t. Need to take out the trash? Just tell your twin. Need to program in Java? Send your twin an email.
Metaprogramming, defined as writing code that writes code by Why The Lucky Stiff, makes scaffolding, associations, validations, and the many magical parts of Rails possible. Implementing metaprogramming techniques can drastically eliminate duplicate code, making your applications far easier to maintain and build. It also lets your code do the work – not you.
CampusSync.com, a client project of ours, is a collaboration site for college students. It has several administration areas that are almost identical, but not a good fit for Rail’s standard scaffolding. The solution to eliminating duplicate code: roll our own metaprogramming solution.
Read more... 
Posted in Heartbeat, HowTo, Ruby on Rails | 3 comments 
CBQ
UPDATE: rails_cron is no longer available, and daemon_generator has moved. BackgrounDRB has gone through a major rewrite, and I’ve got a chapter on Background Processing in The Rails Way by Obie Fernandez. Thanks to Chris Johnson and Douglas F Shearer for the updated information.
Without a way to run long-running tasks, Heartbeat, our 2006 Rails Day Entry, wouldn’t have had a pulse.
Like Heartbeat, most web applications need to run regulary scheduled or long-running tasks at some point in their life-cycle. These tasks are often not inititated by a web request. How can you check the validity of a URL every 15 minutes? How do we get an eCommerce store to calculate the most popular items every 5 hours? How can we re-index our site for searching every day?
If you’ve ever had to do this, chances are you’ve used cron (the *nix tool used to schedule remote tasks) coupled with script/runner. However, wouldn’t it be great if you could maintain your tasks and background “jobs” inside the ruby language, or even better, as part of your Rails application?
Let’s explore two ways to do this: the excellent BackgrounDRb plugin by Ezra Zygmuntowicz, which was used to power Heartbeat, and the fabulous rails_cron by Kyle Maxwell.
Read more... 
Posted in HowTo, Ruby on Rails
Derek
Auto-Complete is a great tool when it provides possible results BEFORE you finish typing. Unfortunately, using Rails’s included AJAX helpers to query the database as you type often results in a large delay before matches are returned.
However, there is a lightning-quick option: pre-fetch the results in a Javascript array.
In a client project, users can add labels to events on their calendar. To prevent users from creating variations of the same label name (i.e. – “favorite” vs. “favorites”), we needed to provide faster auto-complete functionality than that available through Rails’s provided AJAX helpers.
We created a simple helper method for this case (special thanks to Chad Fowler and his Rails Recipes book for the inspiration).
Take a look at the local_auto_complete_field helper method. TXT
To call the function from your views:
<%= local_auto_complete_field('name',@labels) %>
In the above example, we are adding JavaScript-powered auto-complete functionality to the 'name' text field. The JavaScript array is generated by calling #name on each element in the @labels array. To override this behavior:
<%= local_auto_complete_field('name',@labels,
:method => 'description') %>
Here’s to faster auto-completion!