So, for hashes in Ruby you can use hashrockets like this:
corned_beef = {
:ingredient1 => "beef",
:ingredient2 => "potatoes"
}
or the more concise json-ish style.
corned_beef = {
ingredient1: "beef",
ingredient2: "potatoes"
}
Is there a json-ish styled way to catch Ruby exceptions? The normal way is this:
begin
# ...blah blah...
rescue ActiveRecord::RecordNotFound => e
logger.debug { "Where's da beef?" }
rescue => e
logger.debug { "#{e.message}\nBacktrace Begin:\n #
{e.backtrace.join("\n")}" }
else
# ...blah blah...
end
I've started to hate seeing hashrockets in my code, even for this. Someone please educated me.
EDIT: For some reason, this has attracted comments from the kind of people who have code-religious arrogant condescending judgement. This is a forum for questions, if you don't like the question, kindly close your window. Ruby was optimized for programmer happiness. My question is seeking what I deem cleaner sexier code. What is not wanted is an expression of lots of opinions that do nothing toward helping achieve an answer. I am a good programmer with legacy code that has been in production serving billions and is probably older than most of you. Please stop shoveling pointless opinions if it doesn't answer the question. So far, it doesn't look like what I'm seeking exists. That's fine.
If you absolutely want to get rid of it, you can fall back to some of Ruby's Global Variables, specifically
$!
The exception information message set by 'raise'.
$@
Array of backtrace of the last exception thrown.
begin
raise ArgumentError, 'Your argument is invalid'
rescue ArgumentError
puts "#{$!.message}\nBacktrace Begin:\n#{$@.join("\n")}"
# or
puts "#{$!.message}\nBacktrace Begin:\n#{$!.backtrace.join("\n")}"
end
I've never used any of the globals in an any real applications, so not sure what type of things you might want to watch out for (if multiple threads throwing different errors simultaneously* might be an issue, for example).