Class: DynamicLinks::Shortener

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

Overview

Author:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(locker: DynamicLinks::Async::Locker.new, strategy: StrategyFactory.get_strategy(DynamicLinks.configuration.shortening_strategy), storage: ShortenedUrl, async_worker: ShortenUrlJob) ⇒ Shortener

Returns a new instance of Shortener.



6
7
8
9
10
11
12
13
14
# File 'lib/dynamic_links/shortener.rb', line 6

def initialize(locker: DynamicLinks::Async::Locker.new,
               strategy: StrategyFactory.get_strategy(DynamicLinks.configuration.shortening_strategy),
               storage: ShortenedUrl,
               async_worker: ShortenUrlJob)
  @locker = locker
  @strategy = strategy
  @storage = storage
  @async_worker = async_worker
end

Instance Attribute Details

#async_workerObject (readonly)

Returns the value of attribute async_worker.



4
5
6
# File 'lib/dynamic_links/shortener.rb', line 4

def async_worker
  @async_worker
end

#lockerObject (readonly)

Returns the value of attribute locker.



4
5
6
# File 'lib/dynamic_links/shortener.rb', line 4

def locker
  @locker
end

#storageObject (readonly)

Returns the value of attribute storage.



4
5
6
# File 'lib/dynamic_links/shortener.rb', line 4

def storage
  @storage
end

#strategyObject (readonly)

Returns the value of attribute strategy.



4
5
6
# File 'lib/dynamic_links/shortener.rb', line 4

def strategy
  @strategy
end

Instance Method Details

#shorten(client, url) ⇒ String

Returns the shortened url.

Parameters:

  • client (Client)

    the client that owns the url

  • url (String)

    the url to be shortened

Returns:

  • (String)

    the shortened url



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/dynamic_links/shortener.rb', line 19

def shorten(client, url)
  short_url = strategy.shorten(url)

  if strategy.always_growing?
    storage.create!(client: client, url: url, short_url: short_url)
  else
    storage.find_or_create!(client, short_url, url)
  end
  URI::Generic.build({scheme: client.scheme, host: client.hostname, path: "/#{short_url}"}).to_s
rescue => e
  DynamicLinks::Logger.log_error("Error shortening URL: #{e.message}")
  raise e
end

#shorten_async(client, url) ⇒ Object

Parameters:

  • client (Client)

    the client that owns the url

  • url (String)

    the url to be shortened



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dynamic_links/shortener.rb', line 35

def shorten_async(client, url)
  lock_key = locker.generate_lock_key(client, url)

  locker.lock_if_absent(lock_key) do
    short_url = strategy.shorten(url)
    content = {
      url: url,
      short_url: short_url
    }

    async_worker.perform_later(client, url, short_url, lock_key)
  end
rescue => e
  DynamicLinks::Logger.log_error("Error shortening URL asynchronously: #{e.message}")
  raise e
end