Hey there, fellow Ruby developer! Ready to dive into the world of Google Cloud Storage? Let's get your app talking to those cloud-based buckets and files like a pro. We'll be using the google-cloud-storage
gem, so buckle up and let's ride!
Before we jump in, make sure you've got:
First things first, let's get that gem installed:
# In your Gemfile gem 'google-cloud-storage'
Now, hit your terminal with:
bundle install
Easy peasy, right?
Google needs to know it's you knocking on its door. Here's how to introduce yourself:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"
Pro tip: Don't forget to add this to your .gitignore
if you're using version control!
Time to create our magic wand - the Storage object:
require "google/cloud/storage" storage = Google::Cloud::Storage.new
Boom! You're ready to start slinging some cloud storage spells.
bucket = storage.create_bucket "my-awesome-bucket"
file = bucket.create_file "local/path/to/file.txt", "remote-file-name.txt"
file = bucket.file "remote-file-name.txt" file.download "local/path/to/downloaded-file.txt"
storage.buckets.each do |bucket| puts bucket.name end bucket.files.each do |file| puts file.name end
file = bucket.file "remote-file-name.txt" file.delete
file.update do |f| f.content_type = "text/plain" f.metadata = { "key" => "value" } end
url = file.signed_url(method: "GET", expires: 3600)
bucket.update do |b| b.requester_pays = true end
Always wrap your Google Cloud operations in begin/rescue blocks:
begin # Your Google Cloud operation here rescue Google::Cloud::Error => e puts "Error: #{e.message}" end
For better performance, reuse your storage
object instead of creating a new one for each operation.
Here's a quick example using Minitest:
require "minitest/autorun" require "google/cloud/storage" class TestGoogleCloudStorage < Minitest::Test def test_create_bucket storage = Google::Cloud::Storage.new bucket = storage.create_bucket "test-bucket-#{Time.now.to_i}" assert_equal "test-bucket-#{Time.now.to_i}", bucket.name ensure bucket.delete if bucket end end
For mocking responses, check out the google-cloud-storage-testbench
gem. It's a lifesaver for testing without hitting the actual Google Cloud Storage.
And there you have it! You're now equipped to harness the power of Google Cloud Storage in your Ruby applications. Remember, this is just scratching the surface - there's a whole world of advanced features waiting for you in the official docs.
Keep coding, keep learning, and may your uploads always be swift and your downloads never fail!