Created
March 9, 2015 02:41
-
-
Save joelclermont/9703cfb9c8783283c963 to your computer and use it in GitHub Desktop.
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
defmodule Metex.Worker do | |
def loop do | |
receive do | |
{sender_pid, location} -> | |
send(sender_pid, {:ok, temperature_of(location)}) | |
_ -> | |
send(sender_pid, "Unknown message") | |
end | |
loop | |
end | |
def temperature_of(location) do | |
result = url_for(location) |> HTTPoison.get |> parse_response | |
case result do | |
{:ok, temp} -> | |
"#{location}: #{temp} C" | |
:error -> | |
"#{location} not found" | |
end | |
end | |
defp url_for(location) do | |
"http://api.openweathermap.org/data/2.5/weather?q=#{location}" | |
end | |
defp parse_response({:ok, %HTTPoison.Response{body: body, status_code: 200}}) do | |
body |> JSON.decode! |> compute_temperature | |
end | |
defp parse_response(_) do | |
:error | |
end | |
defp compute_temperature(json) do | |
try do | |
temp = (json["main"]["temp"] - 273.15) |> Float.round(1) | |
{:ok, temp} | |
rescue | |
_ -> :error | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
😱 Second case statement is wrong. My bad!
You could probably replace
with
Thanks for pointing it out!