class LinkShortener::Rebrandly
Constants
- API_URL
Public Class Methods
new(url)
click to toggle source
# File lib/link_shortener/rebrandly.rb, line 5 def initialize(url) @url = url end
Public Instance Methods
call()
click to toggle source
# File lib/link_shortener/rebrandly.rb, line 9 def call domain_id = fetch_domain_id body = { destination: @url } body[:domain] = { id: domain_id } if domain_id response = RestClient.post endpoint(:links), body.to_json, headers protocol = protocol_for(response) url = parse_field(response, 'shortUrl') return nil if url.blank? "#{protocol}://#{url}" rescue StandardError => e raise(e) if ENV['DEBUG_LINKS'].present? nil end
Private Instance Methods
endpoint(title)
click to toggle source
# File lib/link_shortener/rebrandly.rb, line 31 def endpoint(title) URI.join(API_URL, title.to_s).to_s end
fetch_domain_id()
click to toggle source
# File lib/link_shortener/rebrandly.rb, line 35 def fetch_domain_id response1 = RestClient.get endpoint(:domains), headers JSON.parse(response1.body).sample.try(:[], 'id') rescue nil end
headers()
click to toggle source
# File lib/link_shortener/rebrandly.rb, line 27 def headers @headers ||= { content_type: :json, accept: :json, apikey: ENV['REBRANDLY_API_KEY'] } end
parse_field(response, title)
click to toggle source
# File lib/link_shortener/rebrandly.rb, line 42 def parse_field(response, title) JSON.parse(response.body).try(:[], title) rescue nil end
protocol_for(response)
click to toggle source
# File lib/link_shortener/rebrandly.rb, line 46 def protocol_for(response) parse_field(response, 'https') ? 'https' : 'http' end