Class: ShortService::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/shortservice.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, name) ⇒ Service

Returns a new instance of Service.



33
34
35
# File 'lib/shortservice.rb', line 33

def initialize(key, name)
  self.key, self.name = key, name
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



9
10
11
# File 'lib/shortservice.rb', line 9

def key
  @key
end

#nameObject

Returns the value of attribute name.



9
10
11
# File 'lib/shortservice.rb', line 9

def name
  @name
end

Class Method Details

.allObject

Get a list of all services



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/shortservice.rb', line 12

def self.all
  @@services ||= begin
    xml = SimpleHttp.get("#{API_URL}/services?format=xml")
    doc = REXML::Document.new(xml)

    services = []

    doc.elements.each("services/service") do |service|
      key, name = service.elements["key"].text, service.elements["name"].text
      services << Service.new(key, name)
    end

    services
  end
end

.find_by_key(key) ⇒ Object

Find a service by key, e.g. “bitly”



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

def self.find_by_key(key)
  all.find { |s| s.key == key }
end

Instance Method Details

#shorten(url) ⇒ Object

Shorten the given URL



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/shortservice.rb', line 38

def shorten(url)
  xml = SimpleHttp.get("#{API_URL}/shorten?url=#{CGI::escape(url)}&service=#{key}&format=xml")
  doc = REXML::Document.new(xml)

  result = doc.elements["result"]

  if result.elements["status"].text == "ok"
    result.elements["url"].text
  else
    raise result.elements["description"].text
  end
end