Class: Whitme
- Inherits:
-
Object
- Object
- Whitme
- Defined in:
- lib/whitme.rb
Overview
Class Method Summary collapse
-
.expand(hash) ⇒ Object
Expands an URL.
-
.short(options = {}) ⇒ Object
Shortens a URL.
Class Method Details
.expand(hash) ⇒ Object
Expands an URL
Returns a Whitme instance with all the (possible) fields filled. Accepts a unique argument with either a hash (e.g. XP45xe3) or a full whit.me URL.
Example
require 'whitme'
url = Whitme.('HQX4P9')
puts url.url.inspect
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/whitme.rb', line 154 def self.(hash) url = WhitmeURL.new if(hash.include? 'http://') hash =~ /hash=(.+)/ hash = $1 end url.hash = hash json = JSON.parse(Net::HTTP.get(URI.parse(url.))) url.url = json['urls'] url.urlnote = json['urlnotes'] url.note = json['note'] url end |
.short(options = {}) ⇒ Object
Shortens a URL
Returns a Whitme instance with the shortened version under the hash
property.
Parameters
-
:url
- a single string or an array of strings containing urls to shorten -
:urlnote
- a single string or an array of strings containing notes associated with the urls -
:note
- a general note to be associated with all the urls shortened -
:hash
- a custom URL alias (for readable shortened URLs). whit.me will return a generated alias if the supplied parameter already exists or is invalid
The only really required field is :url
. If :urlnotes
is supplied, it must have the same size of :url
. Otherwise an ArgumentError is raised.
Example
require 'whitme'
url = Whitme.short(:url => 'http://www.google.com', :note => 'foo')
puts url.hash.inspect
url = Whitme.short(:url => ['http://google.com', 'http://sapo.pt'])
puts url.hash.inspect
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
# File 'lib/whitme.rb', line 95 def self.short( = {}) # we must have at least on url to short raise ArgumentError unless [:url] # if we have multiple notes, we should have the same number of urls if [:urlnote] raise ArgumentError unless [:urlnote].class == [:url].class if([:url].class == Array) raise ArgumentError unless [:url].size == [:urlnote].size end end url = WhitmeURL.new url.url << [:url] if [:url].class == String url.url |= [:url] if [:url].class == Array if [:urlnote] url.urlnote << [:urlnote] if [:urlnote].class == String url.urlnote |= [:urlnote] if [:urlnote].class == Array end url.note = [:note] url.hash = [:hash] uri = URI.parse(url.to_short_url) res = Net::HTTP.start(uri.host, uri.port) do |http| http.get(uri.request_uri, { 'Accept' => 'application/json' }) end json = JSON.parse(res.body) rescue nil if json if json['error'] case json['error'] when 0 raise MalformedURLError when 1 raise MalformedAliasError else raise ArgumentError end else url.hash = json['url'] return url end end end |