Module: ArCache::ClassMethods

Defined in:
lib/ar_cache.rb

Instance Method Summary collapse

Instance Method Details

#cache_find(id, params = nil) ⇒ Object

Perform a query on dabatase and store result in FileSystem.

To uniquify the file name the library calculate MD5 hash for classname, id and params, if result for query exist and isn’t expired it return the cached result otherwise DB is queried and the results is stored in FileSystem. TODO: Support for Eeager-loading



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ar_cache.rb', line 26

def cache_find(id, params=nil)
  class_name = self.class.name
  
  if (params.nil?)
    params = Array.new
  end
  
  filename   = calculate_file_name(id, params)
  if cache_reset?(filename)
    cache_reset(id, params)
  end
  
  if File.exist?(filename)
    content = File.read(filename)
    toReturn = JSON.parse(content)
  else
    toReturn = self.find(id, params)
    File.open(filename, 'w') do |f|
      f.write toReturn.to_json
      f.close
    end
    toReturn = JSON.parse(toReturn.to_json)
  end
  if id == :all
    out = Array.new
    toReturn.each do |obj|
      out << hash_to_obj(obj.values.first)
    end
  else
    toReturn = toReturn.first
    out = hash_to_obj(toReturn.values.first)
  end
  return out
end

#cache_find_all(params = nil) ⇒ Object



69
70
71
# File 'lib/ar_cache.rb', line 69

def cache_find_all(params=nil)
  return cache_find(:all, params)
end

#cache_find_first(params = nil) ⇒ Object



61
62
63
# File 'lib/ar_cache.rb', line 61

def cache_find_first(params=nil)
  return cache_find(:first, params)
end

#cache_find_last(params = nil) ⇒ Object



65
66
67
# File 'lib/ar_cache.rb', line 65

def cache_find_last(params=nil)
  return cache_find(:last, params)
end

#cache_reset(id, params = nil) ⇒ Object



85
86
87
88
# File 'lib/ar_cache.rb', line 85

def cache_reset(id, params=nil)
  filename   = calculate_file_name(id, params)
  File.delete(filename)
end

#cache_reset_all(params = nil) ⇒ Object



81
82
83
# File 'lib/ar_cache.rb', line 81

def cache_reset_all(params=nil)
  return cache_reset(:all, params)
end

#cache_reset_first(params = nil) ⇒ Object



73
74
75
# File 'lib/ar_cache.rb', line 73

def cache_reset_first(params=nil)
  return cache_reset(:first, params)
end

#cache_reset_last(params = nil) ⇒ Object



77
78
79
# File 'lib/ar_cache.rb', line 77

def cache_reset_last(params=nil)
  return cache_reset(:last, params)
end