Created
February 19, 2014 21:27
-
-
Save cheeyeo/9101993 to your computer and use it in GitHub Desktop.
Ruby example of caller specified callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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