Class: GdatastoreCacheStore
- Inherits:
-
Object
- Object
- GdatastoreCacheStore
- Defined in:
- lib/gdatastore_cache_store.rb,
lib/gdatastore_cache_store/version.rb
Instance Method Summary collapse
- #cache_key(key) ⇒ Object
- #delete(key, _ = nil) ⇒ Object
- #exist?(key, _ = nil) ⇒ Boolean
- #fetch(key, _ = nil) ⇒ Object
-
#initialize(project_id, options = { EntityGenre: 'Cache' }) ⇒ GdatastoreCacheStore
constructor
A new instance of GdatastoreCacheStore.
- #keyfy(key) ⇒ Object
- #options ⇒ Object
- #read(key, _ = nil) ⇒ Object
- #write(key, value, _ = nil) ⇒ Object
Constructor Details
#initialize(project_id, options = { EntityGenre: 'Cache' }) ⇒ GdatastoreCacheStore
Returns a new instance of GdatastoreCacheStore.
5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/gdatastore_cache_store.rb', line 5 def initialize(project_id, = { EntityGenre: 'Cache' }) @options = .with_indifferent_access %w(EntityGenre Keyfile).each do |required_key| raise "options should contain #{required_key} parameter" unless @options.keys.include?(required_key) end @entity_genre = @options[:EntityGenre] @datastore = Google::Cloud::Datastore.new( project: project_id, keyfile: @options[:Keyfile] ) end |
Instance Method Details
#cache_key(key) ⇒ Object
47 48 49 |
# File 'lib/gdatastore_cache_store.rb', line 47 def cache_key(key) @datastore.key @entity_genre, keyfy(key) end |
#delete(key, _ = nil) ⇒ Object
39 40 41 |
# File 'lib/gdatastore_cache_store.rb', line 39 def delete(key, _ = nil) @datastore.delete cache_key(key) end |
#exist?(key, _ = nil) ⇒ Boolean
43 44 45 |
# File 'lib/gdatastore_cache_store.rb', line 43 def exist?(key, _ = nil) read(key).present? end |
#fetch(key, _ = nil) ⇒ Object
51 52 53 54 55 56 |
# File 'lib/gdatastore_cache_store.rb', line 51 def fetch(key, _ = nil) result = read(keyfy(key)) return result if result.present? write(keyfy(key), yield) end |
#keyfy(key) ⇒ Object
58 59 60 |
# File 'lib/gdatastore_cache_store.rb', line 58 def keyfy(key) key.to_s end |
#options ⇒ Object
17 18 19 |
# File 'lib/gdatastore_cache_store.rb', line 17 def @options end |
#read(key, _ = nil) ⇒ Object
21 22 23 24 25 26 27 28 29 |
# File 'lib/gdatastore_cache_store.rb', line 21 def read(key, _ = nil) result = @datastore.find cache_key(key) return unless result value = result['value'] return unless value.present? result['kind'] == 'Hash' ? JSON.parse(value).with_indifferent_access : value end |
#write(key, value, _ = nil) ⇒ Object
31 32 33 34 35 36 37 |
# File 'lib/gdatastore_cache_store.rb', line 31 def write(key, value, _ = nil) task = @datastore.entity cache_key(key) do |t| t[:value] = value.is_a?(Hash) ? value.to_json : value t[:kind] = value.class.to_s end @datastore.save task end |