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 |
iex -S mix
Erlang/OTP 17 [erts-6.2] [source-aaaefb3] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]
== Compilation error on file lib/worker.ex ==
** (CompileError) lib/worker.ex:8: function sender_pid/0 undefined
(stdlib) lists.erl:1336: :lists.foreach/2
(stdlib) erl_eval.erl:657: :erl_eval.do_apply/6
😱 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
Line 8 is what throws the error. Nothing is bound to sender_pid in that pattern.