Class: S3FileCache

Inherits:
ApplicationRecord show all
Defined in:
app/models/s3_file_cache.rb

Defined Under Namespace

Classes: S3Object

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.cleaning_directory_and_record!Object



19
20
21
22
23
24
25
26
27
# File 'app/models/s3_file_cache.rb', line 19

def cleaning_directory_and_record!
  limit = Time.zone.now - expire_seconds

  expired_files = where('created_at < ?', limit)
  expired_files.each do |expired_file|
    FileUtils.rm(expired_file.place)
    expired_file.destroy
  end
end

.expire_secondsObject



29
30
31
# File 'app/models/s3_file_cache.rb', line 29

def expire_seconds
  S3FileCacheDownload.expire_seconds.seconds
end

.file_cache_directoryObject



33
34
35
# File 'app/models/s3_file_cache.rb', line 33

def file_cache_directory
  S3FileCacheDownload.file_cache_directory
end

.find_s3_cache_file_or_create!(s3_file_path, bucket_name) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'app/models/s3_file_cache.rb', line 3

def find_s3_cache_file_or_create!(s3_file_path, bucket_name)
  S3FileCache.transaction do
    s3_file_cache = S3FileCache.find_or_create_by!(s3_full_path: s3_file_path, bucket_name: bucket_name)

    if s3_file_cache.expire?
      FileUtils.rm(s3_file_cache.place)
      s3_file_cache.destroy

      s3_file_cache = S3FileCache.create!(s3_full_path: s3_file_path, bucket_name: bucket_name)
    end

    s3_file_cache.fetch!
    s3_file_cache
  end
end

Instance Method Details

#expire?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'app/models/s3_file_cache.rb', line 38

def expire?
  created_at + S3FileCacheDownload.expire_seconds < Time.zone.now
end

#fetch!Object



42
43
44
45
46
47
48
49
50
51
# File 'app/models/s3_file_cache.rb', line 42

def fetch!
  return if File.exist?(place)

  s3_object = S3FileCache::S3Object.new(bucket_name, s3_full_path)
  File.open(place, 'w') do |file|
    s3_object.get.each_line do |line|
      file.write line
    end
  end
end

#filenameObject



57
58
59
# File 'app/models/s3_file_cache.rb', line 57

def filename
  File.basename(s3_full_path)
end

#placeObject



53
54
55
# File 'app/models/s3_file_cache.rb', line 53

def place
  "#{S3FileCache.file_cache_directory}/#{id}"
end