Question

I'm very new to rails and MVC development in general and have been working on an app which makes an external API call to bitly.

I've place the following in the view to generate a shorturl which I then use for fb and twit.

<% Bitly.use_api_version_3
  bitly = Bitly.client
  shareUrl = bitly.shorten("http://example.com/#{id}").short_url%>

Now that I've done this I've realized I'm calling bitly every time this page is viewed. I'm thinking it would be more efficient to do this in the model view than allow it to be cached. Does that make sense, and how would I perform this action in the model?

Was it helpful?

Solution 3

I ended up doing the following in the model

before_save :set_shareUrl 
def set_shareUrl 
 Bitly.use_api_version_3 
 bitly = Bitly.client 
 self.shareURL = bitly.shorten("http://example.com/#{id}").short_url 
end

OTHER TIPS

It is always better to have your APIs in a separate model file, call them through your controllers and pass it on to the corresponding view. Doing that you can regulate your API calls in the controller .

I prefer to put these into a Service which is responsible for dealing with the different external APIs.

As usual there is a RailsCast for creating service objects http://railscasts.com/episodes/398-service-objects

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top