Ruby barewords are insidious

The problem with ruby barewords is that you cannot tell by looking at them what’s going on in them. They hide whether something returns a stored value or performs a complex CPU/IO interaction.

def plain_text_receipt # => Runtime: 5 sec, Network Timeout
  <<-TEXT
  Thank you for your order!
    Product: #{name} - #{price} # => 2 DB queries
    Tax:     #{tax_amount}      # => 1 DB query, 1 API call
    Total:   #{total_amount}    # => 2 DB queries, 1 API call
  TEXT
end

private

def name
  Product.find(id).name
end

def total_amount
  tax_amount + price
end

def tax_amount
  client = TaxServiceClient.new
  price * client.find_tax_rate(address)
end

def price
  Product.find(id).price
end

Code snippets in this post are covered by 0BSD License.



Date
October 31, 2022