Class: CacheIt::ClassDelegate

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

Instance Method Summary collapse

Constructor Details

#initialize(base, config) ⇒ ClassDelegate

Returns a new instance of ClassDelegate.



129
130
131
132
133
134
# File 'lib/cache_it.rb', line 129

def initialize(base, config)
  @base = base
  @config = config
  @base.after_save Proc.new { cache_it.write }
  @base.after_destroy Proc.new { cache_it.delete }
end

Instance Method Details

#configObject



171
172
173
# File 'lib/cache_it.rb', line 171

def config
  @config
end

#find(attrs, options = {}) ⇒ Object



149
150
151
152
153
154
155
# File 'lib/cache_it.rb', line 149

def find(attrs, options = {})
  unless obj = read(attrs, options)
    obj = @base.where(attrs).first
    obj.cache_it.write if obj
  end
  return obj
end

#key(attrs, options = {}) ⇒ Object

Raises:

  • (ArgumentError)


136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/cache_it.rb', line 136

def key(attrs, options = {})
  attrs = attrs.stringify_keys
  index = attrs.keys.sort
  raise ArgumentError, "index not available" unless @config.indexes.include? index
  if options[:counter]
    raise ArgumentError, "not a counter" unless @config.counters.include? options[:counter]
  end
  key = ["CacheIt.v1", @base.name]
  key.push options[:counter] if options[:counter]
  key.push index.map{|name| [name, attrs[name]]}.to_json
  return key.join(":")
end

#read(attrs, options = {}) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/cache_it.rb', line 157

def read(attrs, options = {})
  key = key(attrs)
  obj = nil
  if val = Rails.cache.read(key)
    attributes = val[:attributes]
    obj = @base.new
    obj.send :attributes=, attributes, false
    obj.instance_variable_set("@new_record", false) if obj.id
    obj.instance_variable_set("@changed_attributes", {}) if obj.id
    obj.cache_it.init_counters unless options[:skip_counters]
  end
  return obj
end