Class: StylesheetCache

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/stylesheet_cache.rb

Constant Summary collapse

MAX_TO_KEEP =
50
CLEANUP_AFTER_DAYS =
150

Class Method Summary collapse

Class Method Details

.add(target, digest, content, source_map, max_to_keep: nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/models/stylesheet_cache.rb', line 9

def self.add(target, digest, content, source_map, max_to_keep: nil)
  max_to_keep ||= MAX_TO_KEEP
  old_logger = ActiveRecord::Base.logger

  return false if where(target: target, digest: digest).exists?

  ActiveRecord::Base.logger = nil if Rails.env.development?

  success = create(target: target, digest: digest, content: content, source_map: source_map)

  count = StylesheetCache.count
  if count > max_to_keep
    remove_lower =
      StylesheetCache.where(target: target).limit(max_to_keep).order("id desc").pluck(:id).last

    DB.exec(<<~SQL, id: remove_lower, target: target)
      DELETE FROM stylesheet_cache
      WHERE id < :id AND target = :target
    SQL
  end

  success
rescue ActiveRecord::RecordNotUnique, ActiveRecord::ReadOnlyError
  false
ensure
  ActiveRecord::Base.logger = old_logger if Rails.env.development? && old_logger
end

.clean_upObject



37
38
39
# File 'app/models/stylesheet_cache.rb', line 37

def self.clean_up
  StylesheetCache.where("created_at < ?", CLEANUP_AFTER_DAYS.days.ago).delete_all
end