LoginSignup
6
7

More than 5 years have passed since last update.

Rails3で、bitly.comを利用した短縮URLを作成する

Posted at

パラメータがつきまくって長いURLが、twitterやfacebookでのシェア時に邪魔くさかった際に、短縮URLサービスを使った。

gemがあった

'bitly'というgemを利用するとカンタンだった。
https://github.com/philnash/bitly

1. bitlyのAPI利用

  1. bitlyのアカウント作成

  2. bitlyのUsernameとAPI Keyを取得
    http://bitly.com/a/your_api_key)

2. gemfileに書いてbundle install

Gemfile
gem 'bitly'
$ bundle install

3. コードをちょっとだけ書く

今回はhelperに書いたので、その例を。

app/helpers/hoge_helper.rb
module HogeHelper
  require 'bitly'

  def get_share_url(page_url) # あるページの短縮URLを生成するヘルパー
    Bitly.use_api_version_3 # この行はほんとに必要なのかよく分からない
    bitly = Bitly.new('bitly Username', 'bitly API Key')
    bitly.shorten(page_url).short_url
  end 
end

これでview側で呼び出したりして使ったらよい。

参考

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7