Search code examples
ruby-on-railsrubyformattingpackingruport

Text Formatting in Ruby (For Packing Slips)


I need to generate formatted text packing slips for a Ruby on Rails project I'm working on. I'm considering using Ruport or just formatting it myself in a string and outputting it to text. The only challenge is justifying all of the output appropriately. It needs to look something like this, always aligned properly. Any recommendations?

Company Name
(T) 1-800-123-1234
(E) [email protected]

BILL TO: CUSTOMER NAME                   SHIP TO: CUSTOMER NAME
123 Some Street                          321 Some Street
Address etc.                             Address etc.

Date: 2010-03-12 16:30
Payment Number: 1234-123456

LN  NAME             SKU           DESCRIPTION             QTY    PRICE      TOTAL
----------------------------------------------------------------------------------
001 Product name     GUDB 012 HGQ  product description     2      52.99     105.98
         - Color

Solution

  • As FM already suggested, you can use sprintf:

    "%10s %-10s %10s" % ['abc', 'def', 'ghi'] # use negative numbers for left alignment
    #=> "       abc def               ghi"
    

    And if you need something more sophisticated, try using some standard templating engine, such as erb...