I am calling an API from a Rails model and I would like to raise an error if the API returns on non-200 code. Otherwise I want to cache/lazy-load the data. This is my method:
def data
@data ||= SNL.get_list(name)
raise StandardError, @data.inspect unless @data.success?
@data
end
This works but I was wondering if I can accomplish this in one line. I tried using the and operator combined with an unless but couldn’t get it to work.
Update: I have accepted tokland’s answer because I asked for one line and he/she provided two very good solutions. In the end I am actually going to use
def data
@data ||= SNL.get_list(name)
@data.success? ? @data : (raise StandardError, @data.inspect)
end
for readability. I just hated having a third line just to return @data, since an exception will rarely be raised. I feel odiszapc’s answer is a the best compromise of brevity and readability. Thanks everyone.
I wouldn’t strain to write a one-liner, but you can use
tapif you absolutely must:Also with short-circuited logic: