Project

refs-rails

0.0
No release in over 3 years
A simple way to manage string references in a Rails application.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Runtime

>= 0
 Project Readme

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.