Haml: Generating a unique selector for an element
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
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] = user.name
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.
By default Haml will downcase and underscore the class name. So
ForumPost will become
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.