25 Apr

Active Support helpers configuration - Rails Tricks Issue 4


Hi, this week I am bringing you a trick to configure Active Support helpers!


Active Support is a collection of utility classes and extensions to Ruby core and standard library classes. It provides quite a few valuable data formatting helpers, and if you want to change their formatting settings globally, you can do so by utilizing Rails’ localization.


One such a helper is number_to_currency, which takes precision, unit, delimiter, format, negative_format, and strip_insignificant_zeros as options when you call the helper. If you want to strip insignificant zeros globally, instead of passing the same option over and over to the helper in your code, you can just change the option in your locale file:

f892d2c5-bed1-4f4b-8688-b0d2b3cb8c43.png 44.9 KB

There is also the number_to_human_size helper, which has delimiter, precision, significant, and strip_insignificant_zero options. You can change those globally in the locale file too:

628fc3ff-eb58-40a2-8e33-b7383bbbf4f3.png 139 KB

Dates are also often formatted into specific formats within an application by calling to_s(:date_format), which is deprecated now in favor of to_fs(:date_format). If you want to use a custom format, you can do so in the locale file:

4d09ad69-0652-4d49-85aa-dffce2b27f20.png 94.2 KB

You are probably working with DateTime objects too in your app, so it is a good idea to set the same formats for Time too:

dc1735e2-0d81-4d02-b165-91991a345063.png 71 KB

Last week, I mentioned the Array#to_sentence helper, which can be configured globally from the locale file too:

53f83c5b-7500-40db-bf69-fb9e39bce3c2.png 66.7 KB

That’s it for this week. Until next time!