hungle00 / hungle00.github.io

My Personal Blog
https://hungle00.github.io/
1 stars 0 forks source link

Rails helpers tips for writing better view #10

Open hungle00 opened 1 year ago

hungle00 commented 1 year ago

1. DOM id convention with dom_id

The dom_id helper takes a string or any object as an argument that can be converted to a dom_id. And it helps us convert an object into a unique id like this:

post = Post.find(10)
dom_id(post)               # => "post_10"
dom_id(post, new_comment)  # => "new_comment_post_10"

dom_id helper is introduced a long time and is become more valuable when working with Hotwire concept like Turbo frame or Turbo stream.

Turbo Frames and the dom_id helper

Because turbo_frame_tag uses the dom_id helper under the hood, so when we write

post = Post.find(1)
turbo_frame_tag(post)

It will return

<turbo-frame id="post_1"></turbo_frame>

One of the most common use cases of Turbo Frame is in-line editing. For example, inline editing comment

2. Conditionally class name with class_names

class_names helper is supported from Rails 6.1, make easier to conditionally apply class names in views.