Class: DynamicLinks::ShorteningStrategies::RedisCounterStrategy

Inherits:
BaseStrategy
  • Object
show all
Defined in:
lib/dynamic_links/shortening_strategies/redis_counter_strategy.rb

Constant Summary collapse

MIN_LENGTH =
12
REDIS_COUNTER_KEY =
"dynamic_links:counter".freeze

Constants inherited from BaseStrategy

BaseStrategy::BASE62_CHARS

Instance Method Summary collapse

Constructor Details

#initializeRedisCounterStrategy

Returns a new instance of RedisCounterStrategy.



14
15
16
17
# File 'lib/dynamic_links/shortening_strategies/redis_counter_strategy.rb', line 14

def initialize
  # TODO: use pool of connections
  @redis = Redis.new
end

Instance Method Details

#shorten(url, min_length: MIN_LENGTH) ⇒ String

Shortens the given URL using a Redis counter

Parameters:

  • url (String)

    The URL to shorten

Returns:

  • (String)

    The shortened URL, 12 characters long



22
23
24
25
26
27
# File 'lib/dynamic_links/shortening_strategies/redis_counter_strategy.rb', line 22

def shorten(url, min_length: MIN_LENGTH)
  counter = @redis.incr(REDIS_COUNTER_KEY)

  short_url = base62_encode("#{counter}#{url.hash.abs}".to_i)
  short_url.ljust(min_length, '0')
end