Class: FreshRedis::Key

Inherits:
Object
  • Object
show all
Defined in:
lib/fresh_redis/key.rb

Constant Summary collapse

DEFAULT_OPTIONS =

TODO remove concept of time from a key. Just be about redis key, freshness, granularity

{
  :freshness => 60 * 60, # 1 hour
  :granularity => 1 * 60 # 1 minute
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_key, freshness, granularity) ⇒ Key

Returns a new instance of Key.



26
27
28
29
30
# File 'lib/fresh_redis/key.rb', line 26

def initialize(base_key, freshness, granularity)
  @base_key     = base_key
  @freshness    = freshness
  @granularity  = granularity
end

Instance Attribute Details

#freshnessObject (readonly)

Returns the value of attribute freshness.



24
25
26
# File 'lib/fresh_redis/key.rb', line 24

def freshness
  @freshness
end

Class Method Details

.build(*args) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/fresh_redis/key.rb', line 12

def self.build(*args)
  raise "Don't know how to build FreshRedis::Key for #{args.inspect}" unless args[0]

  return args[0] if Key === args[0] # early exit if we've already got a key

  base_key = args[0]
    
  options = DEFAULT_OPTIONS.merge(args[1] || {})

  self.new(base_key, options[:freshness], options[:granularity])
end

Instance Method Details

#==(other) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/fresh_redis/key.rb', line 44

def ==(other)
  same = true
  same &= Key === other
  same &= @base_key     == other.instance_variable_get(:@base_key)
  same &= @freshness    == other.instance_variable_get(:@freshness)
  same &= @granularity  == other.instance_variable_get(:@granularity)
  same
end

#redis_keyObject



32
33
34
# File 'lib/fresh_redis/key.rb', line 32

def redis_key
  [@base_key, normalize_time(Time.now.to_i, @granularity)].join(":")
end

#timestamp_bucketsObject



36
37
38
39
40
41
42
# File 'lib/fresh_redis/key.rb', line 36

def timestamp_buckets
  t = Time.now.to_i

  from = normalize_time(t - @freshness, @granularity)
  to = normalize_time(t, @granularity)
  (from..to).step(@granularity).map{|timestamp| [@base_key, timestamp].join(":") }
end