views:

80

answers:

2

I have a Rails app where people have a profile page - http://prettylongdomainname.com/profile_username

To create the profile username, I use a before_create AR hook in my model:

before_create :generate_username

def generate_username
    self.username = a_user_name_i_generated
end

I would also like to save a shortened URL to the user's profile so that when they share things, I can automatically link to their profile page. I decided to take advantage of bit.ly's API to shorten the URL but I am not quite sure where I should put the code.

It makes sense that I should save the shortened URL when creating the user, specifically right after I generate the user's profile_username. However, I need to make an HTTP request out to bit.ly's API to get the shortened URL.

Does anyone know the best way to do this?

Thanks!

+3  A: 

I think you have the right idea with using a callback, but I'd create an observer instead, so as not to pollute the User class with calls out to an external API. Here's more information about observers in rails.

Ben Marini
Should I just use a Net::HTTP to make the request or is there an widely used plugin that will make an API call and return an XML object?
Tony
There are a ton of HTTP client and parsing libs, but you'll have to test them out yourself to know what's best. Net::HTTP could be sufficient. This site will help you out: http://www.ruby-toolbox.com/
Ben Marini
+1  A: 

Assuming you won't be changing any user's profile_username after the initial generation, then I'd agree with Ben's suggestion. Write an observer of the profile model. Watch for the creation (read: initial save) of a profile object, and do your shorten function as a result of that.

Your shorten method could then cover the call out to the external API, and adding the new URL to the model instance. Keep your validation of the shortened URL in the model code itself.

Marc L