Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Exceptions cheatsheet from Avdi Grimm talk
# exceptions cheatsheet from Avdi Grimm talk
# talk: http://confreaks.net/videos/523-roa2011-exceptional-ruby
# retry
begin
rescue
retry
end
# simple crash logger
at_exit do
if $! # require 'English' #=> $ERROR_INFO
# your_app_code
end
end
# nested exceptions
class MyError < StandardError
attr_reader :original
def initialize(msg, original=$!)
super msg
@original = original
end
end
# adding context
begin
f = File.open("/a_file")
rescue Exception => e
raise e, "Useful message: #{e.message} - #{f.inspect}"
end
# implement #exception
class Net::HTTPResponse
def exception(msg="HTTP Error")
RuntimeError.new "#{message}: #{code}"
end
end
response = Net::HTTP.get_response "http://makevoid.com/404"
raise response #=> HTTPError 404: NotFound
# system exit
begin
# ...
exit
rescue Exception => e
puts "Rescued: #{e.inspect}, status: #{e.status}"
end
# prints: #<SystemExit: exit> ....
# and then continues!
# There are more that I didn't transcribed and there is an explanation of each one! so watch the video! http://confreaks.net/videos/523-roa2011-exceptional-ruby - @avdi
# more code snippets from his other presentation @railsconf
# http://avdi.org/talks/confident-code-railsconf-2011/
# pathname is more than a string
require 'pathname'
path = Pathname "/home/makevoid/.irb-history"
open path
# prefer Array() over .to_a
Array([1,2,3]) # => [1, 2, 3]
Array("foo") # => ["foo"]
Array(nil) # => []
# assertions
def assert(value, message="Assertion failed")
raise Exception, message, caller unless value
end
options[:message] and
assert(options[:message].to_s !~ /^\s*$/
# guard clause
def say(message, options={})
return "" if message.nil?
# ...
end
# kill nil: use fetch
{}.fetch(:required_opt)
opt = {}.fetch(:required_opt) do
raise ArgumentError, "Missing option!"
end
options.fetch(:width) {40} # default value
# basic null object
class NullObject
def method_missing(*args, &block)
self
end
def nil?; true; end
end
def Maybe(value)
value.nil? ? NullObject.new : value
end
# usage
def slug(text)
Maybe(text).downcase.strip.tr_s('^a-z0-9', '-')
end
slug("Confident Code") # => "confident-code"
slug(nil) # => #<NullObject:0xb780863c>
# popen - opens a pipe (not related but useful)
IO.popen("ls"){ |p| p.read.split }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment