Module: NoBrainer::Criteria::Cache

Extended by:
ActiveSupport::Concern
Defined in:
lib/no_brainer/criteria/cache.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.reload_on(*methods) ⇒ Object



69
70
71
72
73
74
75
76
# File 'lib/no_brainer/criteria/cache.rb', line 69

def self.reload_on(*methods)
  methods.each do |method|
    define_method(method) do |*args, &block|
      reload
      super(*args, &block).tap { reload }
    end
  end
end

.use_cache_for(*methods) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/no_brainer/criteria/cache.rb', line 61

def self.use_cache_for(*methods)
  methods.each do |method|
    define_method(method) do |*args, &block|
      @cache ? @cache.__send__(method, *args, &block) : super(*args, &block)
    end
  end
end

Instance Method Details

#_override_cache(cache) ⇒ Object



57
58
59
# File 'lib/no_brainer/criteria/cache.rb', line 57

def _override_cache(cache)
  @cache = cache
end

#cached?Boolean

Returns:



35
36
37
# File 'lib/no_brainer/criteria/cache.rb', line 35

def cached?
  !!@cache
end

#each(options = {}, &block) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/no_brainer/criteria/cache.rb', line 39

def each(options={}, &block)
  return super unless with_cache? && !options[:no_cache] && block && !@cache_too_small
  return @cache.each(&block) if @cache

  cache = []
  super(options.merge(:no_cache => true)) do |instance|
    block.call(instance)
    cache << instance unless @cache_too_small

    if cache.size > NoBrainer::Config.criteria_cache_max_entries
      cache = []
      @cache_too_small = true
    end
  end
  @cache = cache unless @cache_too_small
  self
end

#inspectObject



14
15
16
17
18
# File 'lib/no_brainer/criteria/cache.rb', line 14

def inspect
  msg = super
  msg = "#{msg} \e[1;37m# #{@cache.size} results cached\e[0m" if @cache && with_cache?
  msg
end

#merge!(criteria, options = {}) ⇒ Object



20
21
22
23
24
25
# File 'lib/no_brainer/criteria/cache.rb', line 20

def merge!(criteria, options={})
  if options[:copy_cache_from] && options[:copy_cache_from].cached?
    @cache = options[:copy_cache_from].instance_variable_get(:@cache)
  end
  super
end

#reloadObject



31
32
33
# File 'lib/no_brainer/criteria/cache.rb', line 31

def reload
  @cache = nil
end

#with_cacheObject



6
7
8
# File 'lib/no_brainer/criteria/cache.rb', line 6

def with_cache
  chain(:with_cache => true)
end

#with_cache?Boolean

Returns:



27
28
29
# File 'lib/no_brainer/criteria/cache.rb', line 27

def with_cache?
  finalized_criteria.options[:with_cache] != false
end

#without_cacheObject



10
11
12
# File 'lib/no_brainer/criteria/cache.rb', line 10

def without_cache
  chain(:with_cache => false)
end