Class: S3Cache
- Inherits:
-
Object
- Object
- S3Cache
- Defined in:
- lib/s3cache.rb
Constant Summary collapse
- VERSION =
"0.9.1"
Instance Method Summary collapse
- #clear ⇒ Object
- #exist?(key) ⇒ Boolean
- #fetch(key, **params) ⇒ Object
-
#initialize(**params) ⇒ S3Cache
constructor
A new instance of S3Cache.
- #read(key, **params) ⇒ Object
- #write(key, contents, **params) ⇒ Object
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 |
# File 'lib/s3cache.rb', line 10 def initialize(**params) if not params.to_h[:bucket_name] puts "requires {:bucket_name => String, (optional) :expires => Integer, (optional) :debug => Boolean }" end @bucket_name = params.to_h[:bucket_name] @expires = params.to_h[:expires] ? params.to_h[:expires] : 32.days @debug = params.to_h[:debug] ? params.to_h[:debug] : false 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? puts "creating bucket #{@bucket_name}" if @debug bucket_create end end end |
Instance Method Details
#clear ⇒ Object
77 78 79 80 81 82 |
# File 'lib/s3cache.rb', line 77 def clear cache_keys.each do |key| puts "deleting key #{key}" if @debug @s3.delete_object({:bucket => @bucket_name, :key => key}) end end |
#exist?(key) ⇒ Boolean
66 67 68 69 70 71 72 73 74 75 |
# File 'lib/s3cache.rb', line 66 def exist?(key) key_name = cache_key( key ) begin response = @s3.get_object({:bucket => @bucket_name, :key => key_name}) rescue response = nil end puts "exists? #{response} #{key_name}" if @debug return !response.nil? end |
#fetch(key, **params) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/s3cache.rb', line 52 def fetch(key, **params) key_name = cache_key( key ) if(exist?(key_name) ) puts "fetch->read #{key_name}" if @debug read (key_name) else puts "fetch->write #{key_name}" if @debug value = yield write(key_name, value) read (key_name) end end |
#read(key, **params) ⇒ Object
31 32 33 34 35 36 37 38 39 |
# File 'lib/s3cache.rb', line 31 def read(key, **params) key_name = cache_key( key ) puts "read #{key_name}" if @debug 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
41 42 43 44 45 46 47 48 49 50 |
# File 'lib/s3cache.rb', line 41 def write(key, contents, **params) key_name = cache_key( key ) puts "write #{key_name}" if @debug @s3.put_object({ bucket: @bucket_name, key: key_name, expires: Time.now + @expires.days, body: Marshal.dump(contents), }) end |