Class: Tweetwine::UrlShortener

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

Instance Method Summary collapse

Constructor Details

#initialize(rest_client, options) ⇒ UrlShortener

Returns a new instance of UrlShortener.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/tweetwine/url_shortener.rb', line 3

def initialize(rest_client, options)
  @rest_client = rest_client
  options = Options.new(options, "URL shortening")
  @method = (options[:method] || :get).to_sym
  @service_url = options.require :service_url
  @url_param_name = options.require :url_param_name
  @extra_params = options[:extra_params] || {}
  if @method == :get
    tmp = []
    @extra_params.each_pair { |k, v| tmp << "#{k}=#{v}" }
    @extra_params = tmp
  end
  @xpath_selector = options.require :xpath_selector
end

Instance Method Details

#shorten(url) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tweetwine/url_shortener.rb', line 18

def shorten(url)
  require "nokogiri"
  rest = case @method
  when :get
    tmp = @extra_params.dup
    tmp << "#{@url_param_name}=#{url}"
    service_url = "#{@service_url}?#{tmp.join('&')}"
    [service_url]
  when :post
    service_url = @service_url
    params = @extra_params.merge({ @url_param_name.to_sym => url })
    [service_url, params]
  else
    raise "Unrecognized HTTP request method"
  end
  response = @rest_client.send(@method, *rest)
  doc = Nokogiri::HTML(response)
  doc.xpath(@xpath_selector).first.to_s
end