This article was originally published on Rails Designer
Black Friday Alert! π€ Rails Designer is now available with a discount up to 50% π€©
If you use Hotwire with Rails, you have most likely used dom_id
. It's a clever, little helper to give a unique id to an element. This helps to easily target an element with Turbo Streams (to update, append or delete).
You use it like this:
dom_id(User) # => "new_user"
dom_id(User.find(42)) # => "user_42"
It is this last example I have issues with. As it exposes the primary id of that record. Depending on your app, you might not care, but when you run a (SaaS) business, this might be sensitive business information you don't want exposed.
So I created a little gem, called stealth_dom_id.
It's based on an a small class I added in my lib
folder for years (there might be more candidates in there for gems π€«). It works like this:
dom_id(User.find(42), attribute: :public_id) # "user_a1b2c3"
You can also, just like with the unstealthy dom_id, pass a prefix attribute:
dom_id(User.find(42), :admin, attribute: :public_id) # "admin_user_a1b2c3"
If you use dom_id
in your Rails projects, I am sure you will love it. Check it out on GitHub.
Top comments (1)
This is a fascinating idea.
Thank you for doing this