Posted 2 months 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 generate 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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 1 month 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