Class: Oso

Inherits:
Object
  • Object
show all
Includes:
Timeout
Defined in:
lib/oso.rb

Overview

A simple client for the Oso URL shortener.

Constant Summary collapse

Error =

Raised for any error.

Class.new StandardError
VERSION =

Duh.

"1.0.1"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url = nil) ⇒ Oso

Create a new instance, optionally specifying the server url. See the url property for defaults and fallbacks.



43
44
45
46
47
48
49
# File 'lib/oso.rb', line 43

def initialize url = nil
  url = url || ENV["OSO_URL"] || "http://localhost:9292"
  url = "http://#{url}" unless /^http/ =~ url

  @url = URI.parse url
  @url.path = "/" if @url.path.empty?
end

Instance Attribute Details

#urlObject (readonly)

A URI. Where does the Oso server live? If unspecified during initialization it’ll default to the contents of the OSO_URL environment variable. If that’s unset, it’s "http://localhost:9292".



38
39
40
# File 'lib/oso.rb', line 38

def url
  @url
end

Class Method Details

.instanceObject

:nodoc:



20
21
22
# File 'lib/oso.rb', line 20

def self.instance
  @instance ||= new
end

.shorten(*args) ⇒ Object

A static helper if you don’t want to create new instances of the Oso class. Set the OSO_URL environment variable to control the server location. See initialize for more information.



29
30
31
# File 'lib/oso.rb', line 29

def self.shorten *args
  instance.shorten(*args)
end

Instance Method Details

#shorten(url, options = {}) ⇒ Object

Create a short URL for url. Pass a :life option (integer, in seconds) to control how long the short URL will be active. Pass a :limit option to control how many times the URL can be hit before it’s deactivated. Pass a :name option to explicitly set the shortened URL.

shorten will raise an Oso::Error if network or server conditions keep url from being shortened in one second.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/oso.rb', line 60

def shorten url, options = {}
  params = options.merge :url => url

  params[:life]  &&= params[:life].to_i
  params[:limit] &&= params[:limit].to_i

  timeout 1, Oso::Error do
    begin
      res = Net::HTTP.post_form @url, params
    rescue Errno::ECONNREFUSED
      raise Oso::Error, "Connection to #@url refused."
    rescue Timeout::Error
      raise Oso::Error, "Connection to #@url timed out."
    rescue Errno::EINVAL, Errno::ECONNRESET, EOFError => e
      raise Oso::Error, "Connection to #@url failed. (#{e.class.name})"
    rescue Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError => e
      raise Oso::Error, "#@url provided a bad response. (#{e.class.name})"
    end

    case res.code.to_i
    when 201 then return res.body
    else raise Oso::Error, "Unsuccessful shorten #{res.code}: #{res.body}"
    end
  end
end