Class: FreshRedis::Key

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

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :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.



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

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.



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

def freshness
  @freshness
end

Class Method Details

.build(*args) ⇒ Object



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

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



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

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



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

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

#timestamp_bucketsObject



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

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.to_i].join(":") }
end