Search code examples
ruby-on-railsrubymodel-view-controllerbit.ly

Where should I create a shortened URL to my users' profile page for MVC architecture?


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!


Solution

  • 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.