Module: SidekiqSmartCache::Model::ClassMethods

Defined in:
lib/sidekiq_smart_cache/model.rb

Instance Method Summary collapse

Instance Method Details

#make_action_cacheable(name, options = {}) ⇒ Object



44
45
46
47
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
# File 'lib/sidekiq_smart_cache/model.rb', line 44

def make_action_cacheable(name, options = {})
  cache_tag = options[:cache_tag] || [cache_prefix, self.name, name].join('.')
  cache_options = options.slice(:expires_in, :job_interlock_timeout)
  instance_method = options[:instance_method]
  without_caching_name = "#{name}_without_caching"
  promise_method_name = "#{name}_promise"

  promise_method = ->(*args) do
    promise_args = cache_options.merge(
      method: without_caching_name,
      args: args
    )

    if instance_method
      promise_args[:klass] = self.class.name
      promise_args[:object_param] = to_param
    else
      promise_args[:klass] = self.name
    end
    SidekiqSmartCache::Promise.new(**promise_args)
  end

  if_available_method = ->(*args) do
    send(promise_method_name, *args).existing_value
  end

  cache_tag_method = ->(*args) do
    send(promise_method_name, *args).cache_tag
  end

  with_caching_method = ->(*args) do
    send(promise_method_name, *args).fetch(24.hours) # close enough to forever?
  end

  without_caching_method = ->(*args) do
    method(name).super_method.call(*args)
  end

  refresh_method = ->(*args) do
    send(promise_method_name, *args).perform_now
  end

  prefix_module = Module.new
  prefix_module.send(:define_method, "#{name}_if_available", if_available_method)
  prefix_module.send(:define_method, "#{name}_cache_tag", cache_tag_method)
  prefix_module.send(:define_method, name, with_caching_method)
  prefix_module.send(:define_method, without_caching_name, without_caching_method)
  prefix_module.send(:define_method, promise_method_name, promise_method)
  prefix_module.send(:define_method, "refresh_#{name}", refresh_method)

  if instance_method
    prepend prefix_module
  else
    singleton_class.prepend prefix_module
  end
end

#make_class_action_cacheable(name, options = {}) ⇒ Object



101
102
103
# File 'lib/sidekiq_smart_cache/model.rb', line 101

def make_class_action_cacheable(name, options = {})
  make_action_cacheable(name, options)
end

#make_instance_action_cacheable(name, options = {}) ⇒ Object



105
106
107
# File 'lib/sidekiq_smart_cache/model.rb', line 105

def make_instance_action_cacheable(name, options = {})
  make_action_cacheable(name, options.merge(instance_method: true))
end