Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Created February 19, 2014 21:27
Show Gist options
  • Save cheeyeo/9101993 to your computer and use it in GitHub Desktop.
Save cheeyeo/9101993 to your computer and use it in GitHub Desktop.
Ruby example of caller specified callback
require 'ostruct'
require 'open-uri'
require 'json'
class TemperatureApiError < StandardError
end
class CheeError < StandardError
end
DEFAULT_FALLBACK = ->(error) { raise }
def get_temp(query, &fallback)
fallback ||= DEFAULT_FALLBACK
key = ENV['WUNDERGROUND_KEY']
url = "http://api.wunderground.com/api/#{key}/conditions/q/#{query}.json"
data = open(url).read
JSON.parse(data)['current_observation']['temp_f']
rescue => error
fallback.call(error)
end
# get_temp("00000") => defaults to the DEFAULT_FALLBACK
# get_temp("00000") do |error|
# raise TemperatureApiError, error.message
# end
tst = ->(error) { raise TemperatureApiError, error.message }
get_temp("00000", &tst)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment