lakeIn231
lakeIn231

Reputation: 1315

Using a ternary if the condition block is short

I've got a piece of that is working, but I've been advised that I should use a ternary if the condition block is short.

module PayerContractsHelper

  def showPayerContractRate(val)
    json_val = JSON.parse(val)
    if(json_val['amount'].present?)
      "display:block"
    else
      "display:none"
    end
  end

end

How exactly can I make this a ternary with this piece of code? I assume it will be less code and more precise. How can I make this happen?

Upvotes: 1

Views: 181

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176562

The ternary conditions is defined as:

condition ? if-true : if-false

In your case the following code

json_val = JSON.parse(val)
if json_val['amount'].present?
  "display:block"
else
  "display:none"
end

will become

JSON.parse(val)['amount'].present? ? "display:block" : "display:none"

or

json_val = JSON.parse(val)
json_val['amount'].present? ? "display:block" : "display:none"

The following version is the most readable to me

module PayerContractsHelper

  def showPayerContractRate(val)
    json_val = JSON.parse(val)
    "display:" + (json_val['amount'].present? ? "block" : "none")
  end

end

Also note that the Ruby naming convention for methods is underscore_case:

module PayerContractsHelper

  def show_payer_contract_rate(val)
    json_val = JSON.parse(val)
    "display:" + (json_val['amount'].present? ? "block" : "none")
  end

end

Upvotes: 5

Related Questions