mr_muscle
mr_muscle

Reputation: 2900

Rails merge string to existing one when if true

I'm using gem prawn for PDF generation. I want to create table using that gem to do so I'm gonna use make_cell from that gem, as follow:

  make_cell(
    content: "#{cash_transaction[:transaction_date]}
              \n#{cash_transaction[:creation_date]}
              \n#{cash_transaction[:deletion_date]}"
  )

The thing is when deletion_date(cash_transaction) is nil it will print we creation_date and empty line (which comes from \n#{cash_transaction[:deletion_date]}. How to prevent such a situation in more elegant way than below:

  if cash_transaction[:deletion_date]
    make_cell(
      content: "#{cash_transaction[:transaction_date]}
                \n#{cash_transaction[:creation_date]}
                \n#{cash_transaction[:deletion_date]}"
    )
  else
    make_cell(
      content: "#{cash_transaction[:transaction_date]}
                \n#{cash_transaction[:creation_date]}"
    )
  end

Upvotes: 0

Views: 110

Answers (2)

SteveTurczyn
SteveTurczyn

Reputation: 36860

I'd suggest you buld the string then pass it to make_cell

content = "#{cash_transaction[:transaction_date]}
           \n#{cash_transaction[:creation_date]}"

content << "\n#{cash_transaction[:deletion_date]} if cash_transaction[:deletion_date]

make_cell(content: content)

Upvotes: 1

eux
eux

Reputation: 3282

How about this:

deletion = cash_transaction[:deletion_date]
deletion = deletion ? "\n#{deletion}" : ''

make_cell(
  content: "#{cash_transaction[:transaction_date]}
            \n#{cash_transaction[:creation_date]}
            #{deletion}"
)

Upvotes: 0

Related Questions