Formatting Boolean Values in Rails
One thing that is missing from the Rails view system (ActionView) is the ability to easily and DRYly format boolean values. I would like to write something like the following examples into my
<%# should output 'true' or 'false' depending on the value of the boolean %> <%=b some_boolean_value %> <%# should output the appropriate string given in the options hash %> <%=b some_other_boolean, :true => 'yes', :false => 'no' %>
It would be even nicer if that imaginary
b helper could easily internationalize its output appropriately. Here’s what I want:
<%# This should look up the translation of :positive/:negative in the current locale under the given scope %> <%=b a_boolean, :scope => [:my, :boolean, :scope] %> <%# This should look up :maybe/:maybe_not in the [:boolean] scope of the :de locale %> <%=b another_boolean, :locale => :de, :true => :maybe, :false => :maybe_not %>
Long story short: If you agree with me that a helper method like this would be cool, then rejoice! I have already written this portentous
b method and provided it in a Gist for your coding pleasure!
Note the lack of documentation, but I think this blog post gets the point across. Also the method is not overly complicated. You should be able to derive its complete behavioral spectrum from the source code.
One thing that might be worth mentioning, though, is the seemingly awkward choice of default translation keys
:negative. If you are interested in my reasoning behind that, you might want to read this.
Oh and if there already is such functionality provided by Rails or another well known Gem, then please let me know. i just couldn’t find something on Googles first page and so I figured it would be easier to come up with my own solution.
I integrated the changes by hron84 from the comments; the helper now even has a test case! So thanks to hron for this. And yes, I do realise that those comments and commits are quite old by now, but I only now got around to pulling them and mentioning them here in the course of my current blog revival. ;P