Firestore is a NoSql DB created by Google that allows for simple querying. Data is stored as documents within collections. For example, "restaurants" can be a collection and "McDonald's" can be a document with id "mcdonaldsid" and name "McDonald's". To install Firestore, run
gem 'google-cloud-firestore'
and make sure to add
'google-cloud-firestore'
to your Gemfile. Then, to use Firestore in an erb file, require
it and create a firestore object which takes your project_id
and credentials
. Remember that your credentials
file is the entire JSON object while project_id
is one field within that object. You can find this JSON object in your Firestore settings:
require 'google/cloud/firestore'
firestore = Google::Cloud::Firestore.new(
project_id: 'your-project-id',
credentials: '/path/to/your/credentials/file.json'
)
and the entire JSON object, which you can put in a file called initialize_firestore.erb
:
require 'google/cloud/firestore'
firestore = Google::Cloud::Firestore.new({
:project_id => ENV.fetch('GOOGLE_PROJECT_ID'),
:credentials => {
:type => ENV.fetch('GOOGLE_TYPE'),
:project_id => ENV.fetch('GOOGLE_PROJECT_ID'),
:private_key_id => ENV.fetch('GOOGLE_PRIVATE_KEY_ID'),
:private_key => ENV.fetch('GOOGLE_PRIVATE_KEY'),
:client_email => ENV.fetch('GOOGLE_CLIENT_EMAIL'),
:client_id => ENV.fetch('GOOGLE_CLIENT_ID'),
:auth_uri => ENV.fetch('GOOGLE_AUTH_URI'),
:token_uri => ENV.fetch('GOOGLE_TOKEN_URI'),
:auth_provider_x509_cert_url => ENV.fetch('GOOGLE_AUTH_PROVIDER_X509_CERT_URL'),
:client_x509_cert_url => ENV.fetch('GOOGLE_CLIENT_X509_CERT_URL')
}
})
Now onto the fun! In the example below, we are referencing a document holding info for "frank" in the "users" collection:
doc_ref = firestore.doc "users/frank"
Then, we get the contents, which holds metadata like id
and the actual data
:
doc_snapshot = doc_ref.get
puts "Document data: #{doc_snapshot.data}."
You can also get all documents in a collection, create a snapshot on a collection that fires when documents are added, edited, or deleted, filter data, and much more!
Top comments (0)