Using Ruby String Methods to Extract Document IDs from Cloudinary URLs
In my most recent project, a project management app using React, Redux and Rails, I added the ability for a user to upload images via Cloudinary. I followed the steps in this detailed walkthrough to set up the file upload functionality. After implementing the upload capability, I also wanted to implement the ability to remove the files, not only from the Rails database, but from the cloud as well. After all, once a file is deleted from the database and thus no longer being used, why bother storing it in my limited cloud space?
The article briefly mentioned the necessary Ruby code for deleting a file:
Let’s say we wanted to delete the item instance from our database. We might also want to delete the image and video it is associated with on Cloudinary.
To delete an image, we call another method from Cloudinary,
Cloudinary::Uploader.destroy(id). For example, an image URL should be stored in the data as a string.
Our ID would represent the identifier before the
This information can be found in the Cloudinary API docs as well.
Cloudinary URL Structure
Before we figure out how to extract the ID, let’s discuss the structure of the URL in a bit more detail.
Consider the sample URL below:
The URL can be broken down into a few parts.
- base URL:
- cloud name:
- resource type:
- delivery type:
- file id (public_id):
- file extension:
Extracting the file ID from the URL
Now that we know the URL structure, how do we access the elusive ID so that we can use it when calling
Based on the structure of the image URL, I know I want to grab the ID which is located to the immediate right of the last
/ and before the file extension.
rpartition, a Ruby string method, which can be used for just this.
An illustrative example and explanation of how
rpartition works can be found below:
“banana”.rpartition(“n”) will return
[“bana”, “n”, “a”].
rpartition searches from the right of the string (hence the ‘r’ in
rpartition), finding the last occurrence of the substring, and returns an array with 3 elements:
- the part of the string before the last occurrence
- the last occurrence of the substring
- and the part of the string after the last occurrence
(See the docs for
rpartition and chaining it with the Ruby array method
.last, we can isolate and utilize the ID.
Putting it all together
Using the following code as the
destroy method in my
Attachment model, the file will be removed from the cloud as well as the database.
After finding the attachment on line 13, we begin the process of isolating the
First, on line 16, we use
rpartition to save the value of the string starting after the last
/ until the end. Afterwards, we use the Ruby string
split method chained with the Ruby array
first method to isolate just what we need.
Finally, we call the
Cloudinary::Uploader.destroy method on line 19 along with the Rails
attachment.destroy method to delete the file from both the cloud and the database.