Posted almost 4 years 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 Archive .

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 generate the same selector over multiple renderings of the same view.


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

This compiles to:

<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:

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

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Henning Koch
Last edit:
almost 4 years 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 short-lived cookies to improve usability.
Accept or learn more