ruby one-liner for this possible?
Any chance the 2nd and 3rd lines can be combined in an one-liner and hopefully save one valuable开发者_如何学编程?
def self.date_format
record = find_by_key('strftime')
record ? record.value : "%Y-%b-%d'
end
the above function in a Config
model try to fetch a database record by a key, return a default if not found in database.
Even better if can be written in named scope. Thanks
As requested.
Nobody yet has mentioned try, which is perfect for this situation:
value = find_by_key('strftime').try(:value) || "%Y-%b-%d"
You could use:
(find_by_key('strftime').value rescue nil) || "%Y-%b-%d"
though using exceptions is not very efficient.
Does
value = find_by_key('strftime') || "%Y-%b-%d"
work for you?
Do you need to assign a "value" variable at all? If not...
def self.date_format
find_by_key('strftime') || "%Y-%b-%d"
end
精彩评论