Skip to content

Instantly share code, notes, and snippets.

@joelclermont
Created March 9, 2015 02:41
Show Gist options
  • Save joelclermont/9703cfb9c8783283c963 to your computer and use it in GitHub Desktop.
Save joelclermont/9703cfb9c8783283c963 to your computer and use it in GitHub Desktop.
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
@benjamintanweihao
Copy link

😱 Second case statement is wrong. My bad!

You could probably replace

send(sender_pid, "Unknown message")

with

IO.puts "Unknown message")

Thanks for pointing it out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment