Class: DynamicLinks::ShorteningStrategies::RedisCounterStrategy

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

Overview

usage: Using default configuration from DynamicLinks configuration default_strategy = DynamicLinks::ShorteningStrategies::RedisCounterStrategy.new

Using a custom configuration custom_redis_config = { host: ‘custom-host’, port: 6380 } custom_strategy = DynamicLinks::ShorteningStrategies::RedisCounterStrategy.new(custom_redis_config)

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

#initialize(redis_config = nil) ⇒ RedisCounterStrategy

Returns a new instance of RedisCounterStrategy.

Parameters:

  • redis_config (Hash) (defaults to: nil)


15
16
17
18
19
20
21
22
# File 'lib/dynamic_links/shortening_strategies/redis_counter_strategy.rb', line 15

def initialize(redis_config = nil)
  super()

  configuration = redis_config.nil? ? DynamicLinks.configuration.redis_counter_config : DynamicLinks::Configuration::RedisConfig.new(redis_config)
  @redis = ConnectionPool.new(size: configuration.pool_size, timeout: configuration.pool_timeout) do
    Redis.new(configuration.config)
  end
end

Instance Method Details

#always_growing?Boolean

Returns:

  • (Boolean)


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

def always_growing?
  true  # This strategy always generates a new shortened URL
end

#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



31
32
33
34
35
36
37
38
# File 'lib/dynamic_links/shortening_strategies/redis_counter_strategy.rb', line 31

def shorten(url, min_length: MIN_LENGTH)
  @redis.with do |conn|
    counter = conn.incr(REDIS_COUNTER_KEY)
    short_url = base62_encode("#{counter}#{url.hash.abs}".to_i)
    short_url = short_url.ljust(min_length, '0')
    short_url
  end
end