I love code puns, but often it’s difficult to justify committing them into a production codebase. But I came up with a hilarious one today. I was asked to “add that * to the required fields.” There were lots of them. “And make it lighter than the rest of the label.” Well crap, that’s a lot of annoying typing. Maybe I could come up with some vim substitution command, but that’s also a lot of annoying typing. So I guess I’d better get started typing this crap 57 times:

[ruby]f.label :title, 'Title <span class="text-muted">*</span>'.html_safe, class: 'control-label'

Suck. Then I thought of this little helper. It’s shorter, more expressive, and best of all makes hilarious use of Ruby syntax:

[ruby]f.label *required(:title), class: 'control-label'

Now all the required fields really have *’s in the code. Ha! Naturally, it works elegantly with optional titles:

[ruby]f.label *required(:max_rate, 'Maximum Rate'), class: 'control-label'

The helper

I know it’s simple, but here’s the helper code.

def required(field_name, field_title = nil)                                                                          
  field_title ||= field_name.to_s.titleize                                                                           
  return field_name, "#{field_title} <span class='text-muted'>*</span>".html_safe                                    
end