Class: S3Cache

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

Constant Summary collapse

VERSION =
"0.9.2"

Instance Method Summary collapse

Constructor Details

#initialize(**params) ⇒ S3Cache

Returns a new instance of S3Cache.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/s3cache.rb', line 10

def initialize(**params)

  @logger = Rails.logger ? Rails.logger : Logger.new(STDOUT)

  if not params.to_h[:bucket_name]
    @logger.info{ "requires {:bucket_name => String, (optional) :expires => Integer}" }
  end

  @bucket_name = params.to_h[:bucket_name]
  @expires = params.to_h[:expires] ? params.to_h[:expires] : 32.days
  
  if ENV['AWS_ACCESS_KEY_ID'].nil? || ENV['AWS_SECRET_ACCESS_KEY'].nil?
    puts 'Enviroment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be defined. Learn more http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#config-settings-and-precedence'  
  else
    @s3 = Aws::S3::Client.new
    if not bucket_exist?
      @logger.debug( "creating bucket #{@bucket_name}" )
      bucket_create
    end
  end
end

Instance Method Details

#clearObject



79
80
81
82
83
84
# File 'lib/s3cache.rb', line 79

def clear
  cache_keys.each do |key|
    @logger.debug( "deleting key #{key}" )
    @s3.delete_object({:bucket => @bucket_name, :key => key})
  end
end

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
70
71
72
73
74
75
76
77
# File 'lib/s3cache.rb', line 67

def exist?(key)   
  key_name = cache_key( key )
  begin
    response =  @s3.get_object({:bucket => @bucket_name, :key => key_name})
  rescue 
    response = nil
  end
  
  @logger.debug( "exists? #{!response.nil?} #{key_name}" )
  return !response.nil?
end

#fetch(key, **params) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/s3cache.rb', line 53

def fetch(key, **params)
  key_name = cache_key( key )

  if(exist?(key_name) )
    @logger.debug( "fetch->read #{key_name}" )
    read (key_name)
  else
    @logger.debug( "fetch->write #{key_name}" )
    value = yield
    write(key_name, value)  
    read (key_name)    
  end    
end

#read(key, **params) ⇒ Object



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

def read(key, **params)
  key_name = cache_key( key )
  @logger.debug( "read #{key_name}" )
  if exist?(key_name)
    Marshal.load(@s3.get_object({ bucket: @bucket_name, key: key_name }).body.read)
  else
    return false
  end    
end

#write(key, contents, **params) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/s3cache.rb', line 42

def write(key, contents, **params) 
  key_name = cache_key( key )
  @logger.debug( "write #{key_name}" )
  @s3.put_object({ 
    bucket: @bucket_name, 
    key: key_name, 
    expires: Time.now + @expires.days,
    body: Marshal.dump(contents),
  })
end