开发者

Where to put Bit.ly API call in Rails app

I'm planning on using Bit.ly Pro and the Bit.ly API to make my own short urls in a Rails 3 project.

I've got a User and a Note model. And a url structure like this: '/username/1-note-title'.

Now I would like to give each note a short url. But I don't know from where I should do the API call. Right now I got this code in the Note controller but I don't know if that's the right place or how to get the url of the specific note...

url = ???

parsed_json = JSON('http://api.bit.ly/v3/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&longUrl=' + url + '&format=json')

@short_url = parsed_json["data"]["url"]

The JSON object structure just for reference:

{
  "status_code": 200, 
  "data": {
    "url": "http://bit.ly/cmeH01", 
    "hash开发者_StackOverflow社区": "cmeH01", 
    "global_hash": "1YKMfY", 
    "long_url": "http://betaworks.com/", 
    "new_hash": 0
  }, 
"status_txt": "OK"
}

Help wanted, thanks in advance!


I seems that the short url should get created when a new note is created for a given user. In that context it would happen as the result of a create action in the NotesController (typically). Best practice would suggest that the logical responsibility should live the Note model so I would suggest you do the bit.ly shortening implemented in a save callback, either before or after, depending on how critical it is (in the context of your particular app) for a shortened URL to exist.

The challenge is do deal with the error case which is when the bit.ly service is unable to respond to your shortening request at all or is taking too long in so doing. That's when putting it in the callback may not make sense as it could potentially tie up your application when trying to fulfill the request.

If you don't need live URL shortening then you could consider creating shortening requests as queued jobs in a background process to be done asynchronously (retrying as necessary) and be triggered in the aforementioned after_save callback in your Note model

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜