Controlling Presentation with Decorators
It’s common to need to alter an object in some way purely for presentation. In the previous example, we saw two such cases. In the first, we wanted to output numbers with thousands separators, and in the second we wanted to prefix prices with the correct currency symbol.
In essence, we want to create some methods to help with the formatting and display of our data. The only question is where to put them. We could create them as top-level methods, but just like creating top-level variables, this doesn’t feel right. We could monkey patch the built-in Ruby classes in question—in this case, Numeric—to add helper methods like with_commas or with_currency_prefix, but this will pollute all numbers and might ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access