Refs
Instead of scattering magic DOM ID strings throughout your Rails application, define them once and reference them safely in your views and controllers.
# config/refs.rb
Refs.define do
ref :user_settings_form
end
<form id="<%= ref.user_settings_form %>"></form>
turbo_stream.replace ref.user_settings_form
Why?
The standard way to dynamically update HTML content in Ruby on Rails relies heavily on DOM IDs. Managing these IDs can be cumbersome, verbose, and error-prone.
Here's a very simple example of replacing content on the page with a turbo stream. As you can see, you need these two string IDs to remain in sync.
<form id="user-settings-form"></form>
turbo_stream.replace "user-settings-form"
With Refs, you'll catch any errors when the server renders the template instead of in the JavaScript console during a click test.
Read the full motivation behind the gem here: DOM IDs are a real pain in my apps
Installation
Add this line to your application's Gemfile:
gem "refs-rails"
Usage
1. Define Your References
Create a file at config/refs.rb
in your Rails application:
# config/refs.rb
Refs.define do
# Form identifiers
ref :login_form
ref :signup_form
ref :user_settings_form
end
2. Use in Views
Each ref you define is turned into a method on the ref
object and automatically available in your views and controllers:
<form id="<%= ref.login_form %>"></form>
render turbo_stream: turbo_stream.replace ref.login_form
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/jameskerr/refs-rails.
License
The gem is available as open source under the terms of the MIT License.