Class: DynamicLinks::ShorteningStrategies::RedisCounterStrategy
- Inherits:
-
BaseStrategy
- Object
- BaseStrategy
- DynamicLinks::ShorteningStrategies::RedisCounterStrategy
- 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
Instance Method Summary collapse
- #always_growing? ⇒ Boolean
-
#initialize(redis_config = nil) ⇒ RedisCounterStrategy
constructor
A new instance of RedisCounterStrategy.
-
#shorten(url, min_length: MIN_LENGTH) ⇒ String
Shortens the given URL using a Redis counter.
Constructor Details
#initialize(redis_config = nil) ⇒ RedisCounterStrategy
Returns a new instance of RedisCounterStrategy.
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
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
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 |