Class: Truncus::Client

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



11
12
13
14
15
16
17
18
# File 'lib/truncus.rb', line 11

def initialize(options = {})
  self.host = options[:host] || ENV['TRUNCT_HOST'] || 'trunc.us'
  self.port = options[:port] || ENV['TRUNCT_PORT'] || 443

  @http ||= Net::HTTP.new(host, port)
  @http.use_ssl = use_ssl?
  @http.verify_mode = options[:ssl_verify_mode] if options[:ssl_verify_mode]
end

Instance Attribute Details

#hostObject

Returns the value of attribute host.



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

def host
  @host
end

#portObject

Returns the value of attribute port.



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

def port
  @port
end

Class Method Details

.expand_token(token) ⇒ Object

Convenience for instantiating a Client and retrieving a shortened url



22
23
24
# File 'lib/truncus.rb', line 22

def self.expand_token(token)
  new.expand_token(token)
end

.get_token(url) ⇒ Object

Convenience for instantiating a Client, shortening a url, and returning the shortened token



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

def self.get_token(url)
  new.get_token(url)
end

.get_url(url) ⇒ Object

Convenience for instantiating a Client, shortening a url, and returning it as a full url to the shortened version.



36
37
38
39
40
# File 'lib/truncus.rb', line 36

def self.get_url(url)
  client = new
  token = client.get_token(url)
  "http#{'s' if client.use_ssl?}://#{client.host}/#{token}"
end

Instance Method Details

#expand_token(token) ⇒ Object

Expand a token: returns the original URL



55
56
57
58
59
60
61
# File 'lib/truncus.rb', line 55

def expand_token(token)
  url = URI.parse("http#{'s' if use_ssl?}://#{host}/#{token}.json")
  req = Net::HTTP::Get.new(url.path)
  res = @http.request(req)
  data = JSON::parse(res.body)
  data['trunct']['url']
end

#get_token(url) ⇒ Object

Shortens a URL, returns the shortened token



44
45
46
47
48
49
50
51
# File 'lib/truncus.rb', line 44

def get_token(url)
  req      = Net::HTTP::Post.new('/', initheader = {'Content-Type' => 'application/json'})
  req.body = {url: url, format: 'json'}.to_json

  res = @http.request(req)
  data = JSON::parse(res.body)
  data['trunct']['token']
end

#use_ssl?Boolean

Is this client configured to use ssl/tls?

Returns:

  • (Boolean)


65
66
67
# File 'lib/truncus.rb', line 65

def use_ssl?
  port.to_i == 443
end