Class: AmazonAssociate::CachingStrategy::Filesystem

Inherits:
Base
  • Object
show all
Defined in:
lib/amazon_associate/caching_strategy/filesystem.rb

Constant Summary collapse

DEFAULT_DISK_QUOTA =

disk quota in megabytes

200
DEFAULT_SWEEP_FREQUENCY =

frequency of sweeping in hours

2

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.cache_pathObject

Returns the value of attribute cache_path.



14
15
16
# File 'lib/amazon_associate/caching_strategy/filesystem.rb', line 14

def cache_path
  @cache_path
end

.disk_quotaObject

Returns the value of attribute disk_quota.



15
16
17
# File 'lib/amazon_associate/caching_strategy/filesystem.rb', line 15

def disk_quota
  @disk_quota
end

.sweep_frequencyObject

Returns the value of attribute sweep_frequency.



16
17
18
# File 'lib/amazon_associate/caching_strategy/filesystem.rb', line 16

def sweep_frequency
  @sweep_frequency
end

Class Method Details

.cache(request, response) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/amazon_associate/caching_strategy/filesystem.rb', line 18

def cache(request, response)
  path = self.cache_path
  cached_filename = Digest::SHA1.hexdigest(request)
  cached_folder = cached_filename[0..2]

  FileUtils.mkdir_p(File.join(path, cached_folder, cached_folder))

  cached_file = File.open(File.join(path, cached_folder, cached_filename), "w")
  cached_file.puts response.doc.to_s
  cached_file.close
end

.get(request) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/amazon_associate/caching_strategy/filesystem.rb', line 30

def get(request)
  path = self.cache_path
  cached_filename = Digest::SHA1.hexdigest(request)
  file_path = File.join(path, cached_filename[0..2], cached_filename)
  if FileTest.exists?(file_path)
    File.read(file_path).chomp
  else
    nil
  end
end

.initialize_options(options) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/amazon_associate/caching_strategy/filesystem.rb', line 41

def initialize_options(options)      
  #check for required options
  if options[:caching_options].nil? || options[:caching_options][:cache_path].nil?
    raise AmazonAssociate::ConfigurationError, "You must specify caching options for filesystem caching: :cache_path is required"
  end

  #default disk quota to 200MB
  Filesystem.disk_quota = options[:caching_options][:disk_quota] || DEFAULT_DISK_QUOTA

  Filesystem.sweep_frequency = options[:caching_options][:sweep_frequency] || DEFAULT_SWEEP_FREQUENCY

  Filesystem.cache_path = options[:caching_options][:cache_path]

  if Filesystem.cache_path.nil? || !File.directory?(Filesystem.cache_path)
    raise AmazonAssociate::ConfigurationError, "You must specify a cache path for filesystem caching"
  end
  return options
end

.sweepObject



60
61
62
# File 'lib/amazon_associate/caching_strategy/filesystem.rb', line 60

def sweep
  perform_sweep if must_sweep?
end