Skip to content

Instantly share code, notes, and snippets.

@shahryarjb
Last active July 23, 2017 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahryarjb/37e76fb079181943f7ea4483deed49e3 to your computer and use it in GitHub Desktop.
Save shahryarjb/37e76fb079181943f7ea4483deed49e3 to your computer and use it in GitHub Desktop.
defmodule Metex.Coordinator do
def loop(results \\ [], results_expected) do
receive do
{:ok, result} ->
new_results = [result|results]
if results_expected == Enum.count(new_results) do
send self, :exit
end
loop(new_results, results_expected)
:exit -> IO.puts(results |> Enum.sort |> Enum.join(", "))
_ -> loop(results, results_expected)
end
end
end
defmodule Metex do
def temperatures_of(cities) do
coordinator_pid =
spawn(Metex.Coordinator, :loop,[[], Enum.count(cities)])
cities |> Enum.each(fn city ->
worker_pid = spawn(Metex.Worker, :loop,[])
send worker_pid, {coordinator_pid, city}
end)
end
end
defmodule Metex.Worker do
def loop do
receive do
{sender_pid, location} -> send(sender_pid, {:ok, temperature_of(location)})
_ -> IO.puts "don't know how to process this message"
end
loop
end
#new task
def loadbytasks(location) do
bb = Task.async(fn ->
hipi(location)
end)
Task.await bb
end
def hipi(cities) do
cities |> Enum.map(fn cities -> temperature_of(cities)end)
end
defp 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
location = URI.encode(location)
"http://api.openweathermap.org/data/2.5/weather?q=#{location}&appid=#{apikey()}"
end
defp parse_response({:ok, %HTTPoison.Response{status_code: 200, body: body}} ) do
body |> JSON.decode! |> computer_temperature
end
defp parse_response(_) do
:error
end
defp computer_temperature(json) do
try do
temp = (json["main"]["temp"] - 273.15) |> Float.round(1)
{:ok, temp}
rescue
_ -> :error
end
end
defp apikey do
"af206b25b0f2be7c78df109d02a2bb68"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment