Something interesting I discovered today while working on an email is the ljust & rjust methods (think left & right justified) for Ruby strings. What it does is it makes sure that your string has at least a certain number of characters and if it doesn’t it adds some characters. Here’s a small code snippet from the rdocs that is pretty self explaining:
"hello".ljust(4) #=> "hello" "hello".ljust(20) #=> "hello " "hello".ljust(20, '1234') #=> "hello123412341234123"
"hello".rjust(4) #=> "hello" "hello".rjust(20) #=> " hello" "hello".rjust(20, '1234') #=> "123412341234123hello"
This is useful when sending emails with Rails that are plain text emails. It can help you align things that look like columns, like this:
INVOICE ---------------------------------------------------------- Bill to: <%= @account.user.name %> Description Price ---------------------------------------------------------- <%= (@product.name).ljust(36) %> <%= number_to_currency(@product.amount).rjust(21) %> If you have any questions about this invoice, please contact <%= AppConfig['from_email'] %>. Thank you for your business!
This would produce an email that might look like this:
INVOICE ---------------------------------------------------------- Bill to: Michael Jordan Description Price ---------------------------------------------------------- Nike Air shoes $150 If you have any questions about this invoice, please contact support@nike.com Thank you for your business!
