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
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:
# config/locales/en.yml number: currency: format: strip_insignificant_zeros: true
There is also the
number_to_human_size helper, which has
strip_insignificant_zero options. You can change those globally in the locale file too:
# config/locales/en.yml en: number: # Used in NumberHelper.number_to_human_size() and NumberHelper.number_to_human() human: format: # These six are to override number.format and are optional # separator: delimiter: "" precision: 3 # round_mode: significant: true strip_insignificant_zeros: true
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:
# config/locales/en.yml en: date: formats: # Use the strftime parameters for formats. # When no format has been given, it uses default. # You can provide other formats here if you like! default: "%Y-%m-%d" short: "%b %d" long: "%B %d, %Y" day: "%A"
You are probably working with
DateTime objects too in your app, so it is a good idea to set the same formats for
# config/locales/en.yml en: time: formats: default: "%a, %d %b %Y %H:%M:%S %z" short: "%d %b %H:%M" long: "%B %d, %Y %H:%M" day: "%A"
Last week, I mentioned the
Array#to_sentence helper, which can be configured globally from the locale file too:
# config/locales/en.yml en: support: array: words_connector: ", " two_words_connector: " and " last_word_connector: ", and "
That’s it for this week. Until next time!
Did you enjoy reading this? Sign up to the Rails Tricks newsletter for more content like this!
Or follow me on Twitter
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.It is free to use at the moment, and I am grateful for any feedback about it.
If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!