Module: ActiveModelCachers::ActiveRecord::Extension

Defined in:
lib/active_model_cachers/active_record/extension.rb,
lib/active_model_cachers/active_record/patch_rails_3.rb

Instance Method Summary collapse

Instance Method Details

#after_commit(*args, &block) ⇒ Object

after_commit in Rails 3 cannot specify multiple :on EX:

after_commit ->{ ... }, on: [:create, :destroy]

Should rewrite it as:

after_commit ->{ ... }, on: :create
after_commit ->{ ... }, on: :destroy

18
19
20
21
22
23
24
25
# File 'lib/active_model_cachers/active_record/patch_rails_3.rb', line 18

def after_commit(*args, &block) # mass-assign protected attributes `id` In Rails 3
  if args.last.is_a?(Hash)
    if (on = args.last[:on]).is_a?(Array)
      return on.each{|s| after_commit(*[*args[0...-1], { **args[-1], on: s }], &block) }
    end
  end
  super
end

#cache_at(column, query = nil, expire_by: nil, on: nil, foreign_key: nil, primary_key: nil) ⇒ Object


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_model_cachers/active_record/extension.rb', line 16

def cache_at(column, query = nil, expire_by: nil, on: nil, foreign_key: nil, primary_key: nil)
  attr = AttrModel.new(self, column, foreign_key: foreign_key, primary_key: primary_key)
  return cache_belongs_to(attr) if attr.belongs_to?

  query ||= ->(id){ attr.query_model(self, id) }
  service_klass = CacheServiceFactory.create_for_active_model(attr, query)
  Cacher.define_cacher_method(attr, attr.primary_key || :id, [service_klass])

  with_id = true if expire_by.is_a?(Symbol) or query.parameters.size == 1
  expire_class, expire_column, foreign_key = get_expire_infos(attr, expire_by, foreign_key)
  if expire_class
    define_callback_for_cleaning_cache(expire_class, expire_column, foreign_key, on: on) do |id|
      service_klass.clean_at(with_id ? id : nil)
    end
  end
  return service_klass
end

#cache_self(by: :id) ⇒ Object


12
13
14
# File 'lib/active_model_cachers/active_record/extension.rb', line 12

def cache_self(by: :id)
  cache_at(nil, expire_by: self.name, primary_key: by, foreign_key: by)
end

#find_by(*args) ⇒ Object

define #find_by for Rails 3


6
7
8
# File 'lib/active_model_cachers/active_record/patch_rails_3.rb', line 6

def find_by(*args)
  where(*args).order('').first
end

#has_cacher?(column = nil) ⇒ Boolean

Returns:

  • (Boolean)

34
35
36
37
# File 'lib/active_model_cachers/active_record/extension.rb', line 34

def has_cacher?(column = nil)
  attr = AttrModel.new(self, column)
  return CacheServiceFactory.has_cacher?(attr)
end