Fork me on GitHub

Rails Views, Bulletproofing dom_id

2006-07-02

In my eternal quest to stave off DOM ID collision, I recently had to make a few small changes to the original domid]1 script from the indomitable Jamis Buck.

  • Recently, I needed two forms on the same page for two models from the same single-table inheritance table (though that’s not part of the issue), and I wanted to use the same prefix for both. Since the vanilla dom_id scheme removes the class name when a prefix is defined, collision would occur. My modifications ensure the class name is always included– after all, I don’t care how long the DOM ID is– part of the beauty is I don’t even have to know what’s being generated.
  • I removed the :bare prefix option, as I never use it (though some of you may).
  • I replaced dashes with underscores. I prefer dashes, myself (for CSS classes, too), but due to the reported issues with dasherized ids and scriptaculous drag-and-drop (a feature I use very, very rarely), I’m reluctantly letting them go.

Some examples:

>> person = Person.find(:first)
>> person.dom_id
=> "student_1" # Note: The first person is a Student
>> person.`dom_id` 'some_prefix'
=> "some_prefix_student_1"
>> Person.new.dom_id
=> "person_new"
>> Person.new.`dom_id` 'some_prefix'
=> "some_prefix_person_new"

Keep in mind that, since my original posting, a few people have released slightly-modified plugin versions of dom_id (most notably Geoffrey Grosenbach). They might already meet your needs.

Discussion