Cleanest way to justify plain-text columnized layouts?
In a plain-text .erb template, what method would you suggest I use to produce the most maintainable/readable code for something like this:
ITEM DESCRIPTION QTY PRICE
Product Name One 1 $10.00
Another Product With a Longer Name 2 $5.00
Yet Another Item 1 $30.00
Where each of those rows is (obviously) variable, based on the items that have been purchased.
I could calculate the need开发者_如何学Ced whitespace in a helper method, but is this already a solved problem with a more elegant solution?
Looks like one can actually pass a format attribute to the ERB template to do this. I used this trick recently in a pull request for rumm.
My example follows:
Fist the erb template looks like the following:
ID Name
== ====
<% this.each do |flavor| %>
<%= '%-17s %-7s' % [flavor.id, flavor.name] %>
<% end %>
This outputs data that looks like this:
ID Name
== ====
2 512MB Standard Instance
3 1GB Standard Instance
4 2GB Standard Instance
5 4GB Standard Instance
6 8GB Standard Instance
7 15GB Standard Instance
8 30GB Standard Instance
performance1-1 1 GB Performance
performance1-2 2 GB Performance
performance1-4 4 GB Performance
performance1-8 8 GB Performance
performance2-120 120 GB Performance
performance2-15 15 GB Performance
performance2-30 30 GB Performance
performance2-60 60 GB Performance
performance2-90 90 GB Performance
Sounds like you need a plain text table generator. The only one I can think of for ruby is this: https://github.com/visionmedia/terminal-table but there may be others if this one doesn't fit your needs.
I ended up just using printf()
with padding format options. The terminal table thing looked a bit over-complex for this situation, but useful for more complex requirements, such as displaying tabulated result sets.
精彩评论