Skip to content

Instantly share code, notes, and snippets.

@diegodurs
Created January 9, 2018 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegodurs/8c2c4e3d433b06b1111453ddefcf5217 to your computer and use it in GitHub Desktop.
Save diegodurs/8c2c4e3d433b06b1111453ddefcf5217 to your computer and use it in GitHub Desktop.
KeyVal on Google Datastore
require 'google/cloud/datastore'
module Ruba
# This use the Google Datastore as a key value storage.
# One could argue that Memcache would be more appropriate.
# usage:
#
## class DoSomething
## include GoogleKeyVal
##
## # this will be used as the "namespace" of the keys, leave blank
## # to use the name of the current class.
## def self.service_id
## 'DoSomething'
## end
##
## def process
## results = get_gkey(:results)
## if results
## results[:total] += 1
## else
## results = {
## total: 0,
## start: Time.now.utc.to_s
## }
## end
##
## store_gkey(:results, results)
## end
##
## def cleanup
## del_gkey(:results)
## end
## end
module GoogleKeyVal
def store_gkey(key, value)
gkey = Google::Cloud::Datastore::Key.new "GoogleKeyVal", namespaced_key(key)
entity = Google::Cloud::Datastore::Entity.new
entity.key = gkey
entity["value"] = value.to_json
entity["namespace"] = self.class.key_namespace
entity.exclude_from_indexes! "value", true
Ruba.logger.debug "Storing key #{gkey.name} with #{value.to_json}"
self.class._google_datastore.save entity
end
def get_gkey(key)
gkey = Google::Cloud::Datastore::Key.new "GoogleKeyVal", namespaced_key(key)
entities = self.class._google_datastore.lookup gkey
Ruba.logger.debug "Getting key #{gkey.name} with #{entities.first}"
if entities.any?
value = entities.first.properties.to_hash['value']
JSON.parse(value).deep_symbolize_keys if value
end
end
def del_gkey(key)
gkey = Google::Cloud::Datastore::Key.new "GoogleKeyVal", namespaced_key(key)
self.class._google_datastore.delete gkey
end
def namespaced_key(key)
"#{self.class.key_namespace}:#{key}"
end
module ClassMethods
def _google_datastore
@@datastore ||= Google::Cloud::Datastore.new
end
def key_namespace
try(:service_id) || self.name
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment