Last active
April 24, 2016 02:04
-
-
Save JeffCohen/3ff5a1317e52092684e3f376fd001e26 to your computer and use it in GitHub Desktop.
Elixir example
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 HelloPhoenix.MoviesController do | |
use HelloPhoenix.Web, :controller | |
require Logger | |
def show(conn, %{"id" => query}) do | |
results = fetch_by_id(query) | |
# results is a hash that might have a key named "Error" | |
# in which case we need to try to query by title instead of id | |
# Old Code that works: | |
# if elem(results, 1)["Error"] != nil do | |
# results = fetch_by_title(query) | |
# end | |
# This does not work, and feels silly anyway | |
# The first attempt to detect the "Error" doesn't work | |
# And without the no-op line, I get | |
# "no case clause matching: {:ok, %{"Actors" => "Tom H..." | |
case elem(results,1) do | |
{ "Error", _ } -> results = fetch_by_title(query) | |
_ -> # noop | |
end | |
{ :ok, movie } = results | |
render conn, "show.html", movie: movie | |
end | |
defp find_by_id_url(id) do | |
"http://omdbapi.com/?i=#{id}" | |
end | |
defp find_by_title_url(title) do | |
"http://omdbapi.com/?t=#{title}" | |
end | |
def fetch_by_id(id) do | |
find_by_id_url(id) |> HTTPoison.get |> handle_response | |
end | |
def fetch_by_title(title) do | |
find_by_title_url(title) |> HTTPoison.get |> handle_response | |
end | |
defp handle_response({:ok, %HTTPoison.Response{body: body}}) do | |
results = Poison.decode body | |
end | |
defp handle_response({:error, %HTTPoison.Error{reason: reason}}) do | |
{ :error, reason } | |
end | |
end |
napcs
commented
Apr 24, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment