You can make it a little shorter:
financial_document.assets ? financial_document.assets.length : '0'
because
financial_document.assets == !financial_document.assets.nil?
but overall, IMHO there is no less repetitive, only various workarounds. (And this is one of the things I don't like about Ruby that much.) You can make sure that objects are not null (as other people point out here), but you can't do this everywhere. You can wrap nil verification code in helper methods or in start-rescue blocks.
For example, instead of adding the length method to the nil object (which is IMHO a dirty hack), I wrote a helper method - "get get get":
def fd_length(financial_document) financial_document.assets ? financial_document.assets.length : '0' end
Lukas Stejskal
source share