Format with to_s Methods ActiveSupport Provides
Posted on by Gentaro "hibariya" Terada
Today I learned/remembered that to format a number with a delimiter, we can use ActiveSupport::NumericWithFormat#to_s(:delimited)
.
require 'active_support'
require 'active_support/core_ext'
123456789.to_s(:delimited) # => "123,456,789"
Not only that, but this method also provides other formats and takes options to tweak its behavior.
123456789.to_s(:delimited, delimiter: '-') # => "123-456-789"
123456789.to_s(:currency, precision: 3) # => "$123,456,789.000"
123456789.to_s(:human_size) # => "118 MB"
123456789.to_s(:human) # => "123 Million"
Originally, when I need to format a number to a delimited number, I would try to use number_to_delimited provided by ActiveSupport::NumberHelper. But to_s
is handy when we have to do that where the helper is not reachable by default, such as in a serializer class for ActiveModel Serializer. Calling this method passing a format is the same as calling ActiveSupport::NumberHelper.number_to_#{format}.
require 'active_support'
require 'active_support/number_helper'
ActiveSupport::NumberHelper.number_to_delimited(123456789) # => "123,456,789"
ActiveSupport::NumberHelper.number_to_delimited(123456789, delimiter: '-') # => "123-456-789"
ActiveSupport::NumberHelper.number_to_currency(123456789) # => "$123,456,789.00"
ActiveSupport::NumberHelper.number_to_human_size(123456789) # => "118 MB"
ActiveSupport::NumberHelper.number_to_human(123456789) # => "123 Million"
With ActiveSupport, several other objects also take format as an argument of to_s
like below.
require 'active_support'
require 'active_support/core_ext'
Time.now.to_s(:long) # => "March 12, 2021 18:43"
BigDecimal('1234.56789').to_s(:delimited) # => "1,234.56789"