Posted 4 days ago. Visible to the public.

Haml: Generating a unique selector for an element

Having a unique selector for an element is useful to later select it from JavaScript or to update a fragment with an Unpoly.

Haml lets you use square brackets ([]) to generate a unique class name and ID from a given Ruby object. Haml will infer a class attribute from the given object's Ruby class. It will also infer an id attribute from the given object's Ruby class and #id method.

This is especially useful with ActiveRecord instances, which have a persisted #id and will hence generated the same selector over multiple renderings of the same view.

Example

Copy
- @users.each do |user| .row[user] = user.name

This compiles to:

Copy
<div class='user row' id='user_37'>Alice</div> <div class='user row' id='user_38'>Bob</div>

Since the record's #id is part of the generated selector, it will be the same over multiple renderings of the same view.

Controlling the generated string

By default Haml will downcase and underscore the class name. So ForumPost will become forum_post.

You can control the generated string by overriding the #haml_object_ref method in the referenced object:

Copy
class ForumPost < ActiveRecord::Base def haml_object_ref 'forum-comment' end end

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Henning Koch
Last edit:
4 days ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more