Class: CoffeeTable::Cache

Inherits:
Object
  • Object
show all
Includes:
Utility
Defined in:
lib/coffee_table.rb

Instance Method Summary collapse

Methods included from Utility

#method_missing, #underscore

Constructor Details

#initialize(options = {}) ⇒ Cache

initialize for coffee_table. takes options to setup behaviour of cache



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/coffee_table.rb', line 19

def initialize(options={})
  @options = options

  default_enable_cache_to true
  default_redis_namespace_to :coffee_table
  default_redis_server_to "127.0.0.1"
  default_redis_port_to 6379
  default_redis_to nil
  default_ignore_code_changes_to false
  default_compress_content_to true
  default_compress_min_size_to 10240
  default_max_threads_to 5

  if !@options[:redis].nil?
    @redis = @options[:redis]
  elsif @options.has_key?(:redis_url)
    @redis = Redis.new({:url => @options[:redis_url]})
  else
    @redis = Redis.new({:server => @options[:redis_server], :port => @options[:redis_port]})
  end
  rufus_version = Gem::Version.new(Rufus::Scheduler::VERSION)
  if rufus_version >= Gem::Version.new('3.0.0')
    @scheduler = Rufus::Scheduler.new(:max_work_threads )
  else
    @scheduler = Rufus::Scheduler.start_new
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class CoffeeTable::Utility

Instance Method Details

#expire_allObject



121
122
123
# File 'lib/coffee_table.rb', line 121

def expire_all
  keys.map{|key| expire_key(key)}
end

#expire_for(*objects) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/coffee_table.rb', line 129

def expire_for(*objects)
  if defined? Rails
    perform_caching = Rails.application.configure do
      config.action_controller.perform_caching
    end
  else
    perform_caching = true
  end

  if perform_caching
    deleted_keys = []
    unless objects.count == 0
      keys.map{|k| CoffeeTable::Key.parse(k)}.each do |key|
        expire = true
        objects.each do |object|
          if object.class == String || object.class == Symbol
            unless key.has_element?(object)
              expire = false
            end
          elsif object.class == Class
            object_type = underscore(object.to_s)
            unless key.has_element_type?(object_type) || key.has_element_type?(ActiveSupport::Inflector.pluralize(object_type))
              expire = false
            end
          else
            object_type = underscore(object.class.to_s)
            unless key.has_element?("#{object_type.to_sym}[#{object.id}]") or key.has_element?(object_type)
              expire = false
            end
          end
        end
        if expire
          expire_key(key.to_s)
          deleted_keys << key
        end
      end
    end
    deleted_keys
  end
end

#expire_key(key_value) ⇒ Object



114
115
116
117
118
119
# File 'lib/coffee_table.rb', line 114

def expire_key(key_value)
  keys.map{|k| CoffeeTable::Key.parse(k)}.select{|key| key.has_element?(key_value) || key.to_s == key_value }.each do |key|
    @redis.del(key.to_s)
    @redis.srem "cache_keys", key.to_s
  end
end

#fetch(initial_key, *related_objects, &block) ⇒ Object Also known as: get_cache



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/coffee_table.rb', line 48

def fetch(initial_key, *related_objects, &block)
  raise CoffeeTable::BlockMissingError, "No block given to generate cache from" unless block_given?

  # extract the options hash if it is present
  options = {}
  if related_objects[-1].instance_of? Hash
    options = related_objects[-1]
    related_objects = related_objects[0..-2]
  end

  # check objects are valid
  related_objects.flatten.map{|o| raise CoffeeTable::InvalidObjectError, "Objects passed in must have an id method or be a class" unless object_valid?(o)}

  if @options[:ignore_code_changes]
    block_key = ""
  else
    block_source = RubyVM::InstructionSequence.disasm(block.to_proc).to_s.gsub(/\(\s*\d+\)/, "").gsub(/^== disasm.*?$/, "")
    block_key = Digest::MD5.hexdigest(block_source)
  end

  flags = {}



  # if first related_object is integer or fixnum it is used as an expiry time for the cache object
  key = CoffeeTable::Key.new(initial_key, block_key, flags, related_objects)

  if @options[:enable_cache]
    if options.has_key?(:expiry)
      expiry = options[:expiry]
    else
      expiry = nil
    end

    @redis.sadd "cache_keys", key unless @redis.sismember "cache_keys", key.to_s
    if @redis.exists(key.to_s)
      if key.options[:compressed]
        result = marshal_value(@redis.get(key.to_s).gunzip)
      else
        result = marshal_value(@redis.get(key.to_s))
      end
    else
      result = yield

      compress_result = @options[:compress_content] && result.kind_of?(String) && result.length > @options[:compress_min_size]

      if compress_result
        key.add_flag(:compressed => true)
        @redis.set key.to_s, Marshal.dump(result.gzip)
      else
        @redis.set key.to_s, Marshal.dump(result)
      end

      unless expiry.nil?
        @redis.expire key.to_s, expiry
        @scheduler.in "#{expiry}s" do
          @redis.srem "cache_keys", key.to_s
        end
      end
    end
  else
    result = yield
  end
  result
end

#keysObject



125
126
127
# File 'lib/coffee_table.rb', line 125

def keys
  @redis.smembers("cache_keys")
end