How to shorten URLs in Ruby

URL shortener

Install gems:

1
2
gem install bitly
gem install google_url_shortener

Calling bitly shortener in Ruby

File: testbitly.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
require 'bitly'
if ARGV.length != 1
puts 'Usage: ruby testbitly.rb URL'
exit
end
bitlyusername = 'YOUR_USERNAME'
bitlytoken = 'YOUR_TOKEN'
Bitly.use_api_version_3
Bitly.configure do |config|
config.api_version = 3
config.access_token = bitlytoken
end
u = Bitly.client.shorten(ARGV[0])
puts u.short_url

Test

1
ruby testbitly.rb https://www.yuxifan.com

Calling google shortener in Ruby

File: testgoogle.rb

1
2
3
4
5
6
7
8
require 'google_url_shortener'
Google::UrlShortener::Base.api_key = "YOUR_API_KEY"
url = "https://www.yuxifan.com/"
gurl = Google::UrlShortener::Url.new(:long_url => url)
u = gurl.shorten!
puts u

Test

1
ruby testgoogle.rb
Share