-
Notifications
You must be signed in to change notification settings - Fork 2
Numeric value formatting interpolation
lulalala edited this page Apr 19, 2017
·
1 revision
Often we need to interpolate dynamic values inside our error messages, with different formatting styles. For exmaple display a number as currency amount "The amount $12,000 is not enough to make a purchase."
.
Sometimes we also wish to preserve the value without formatting, so we can pass it as JSON data to the client.
Currently we have to do something like this:
# In model
errors.add(:foo, :bar, amount: 1000, amount_formatted: "$1,000")
# In locale file
foo:
bar: "bar %{amount_formatted}"
# In JSON API controller
error_details = errors.details[:foo].first
render json: {
error: error_details[:error]
amount: error_details[:amount]
}
It would be nice if we can simplify writing the formatting code somehow.
Instead of passing numbers, pass an object instead.
errors.add(:foo, :bar, date: Format.new(date))
The object can provide two methods, one for formatting, another as raw value:
class Format
def formatted
@value.strftime("%D")
end
def raw
@value
end
end