Class: LocalDataCacher

Inherits:
Object
  • Object
show all
Defined in:
lib/local_data_cacher.rb

Instance Method Summary collapse

Constructor Details

#initialize(dir) ⇒ LocalDataCacher



5
6
7
8
# File 'lib/local_data_cacher.rb', line 5

def initialize(dir)
    @cache_dir = dir
    FileUtils.mkdir_p(@cache_dir) unless Dir.exists?(@cache_dir)
end

Instance Method Details

#get_cached_data_info(file_name) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/local_data_cacher.rb', line 32

def get_cached_data_info(file_name)
    if(File.exists?("#{@cache_dir}/#{file_name}"))
        age = ((Time.now - File.stat("#{@cache_dir}/#{file_name}").mtime).to_i / 86400.0).round.to_i
        return "#{@cache_dir}/#{file_name} is currently about #{age} day(s) old"
    else
        return "#{@cache_dir}/#{file_name} does not exist"
    end
end

#load_data(file_name) ⇒ Object



22
23
24
# File 'lib/local_data_cacher.rb', line 22

def load_data(file_name)
    return YAML.load_file("#{@cache_dir}/#{file_name}")
end

#save_data(data, file_name) ⇒ Object



26
27
28
29
30
# File 'lib/local_data_cacher.rb', line 26

def save_data(data, file_name)
    File.open("#{@cache_dir}/#{file_name}", 'w+') do |f|
        f.puts data.to_yaml
    end
end

#use_cached_data?(file_name, num_days_cache_file: 7) ⇒ Boolean



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/local_data_cacher.rb', line 10

def use_cached_data?(file_name, num_days_cache_file: 7)
    if(File.exists?("#{@cache_dir}/#{file_name}"))
        if((Time.now - File.stat("#{@cache_dir}/#{file_name}").mtime).to_i / 86400.0 >= num_days_cache_file.to_f)
            return false
        else
            return true
        end
    else
        return false
    end
end