Skip to content

Instantly share code, notes, and snippets.

@JeffCohen
Last active April 24, 2016 02:04
Show Gist options
  • Save JeffCohen/3ff5a1317e52092684e3f376fd001e26 to your computer and use it in GitHub Desktop.
Save JeffCohen/3ff5a1317e52092684e3f376fd001e26 to your computer and use it in GitHub Desktop.
Elixir example
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
Copy link

napcs commented Apr 24, 2016

case get_movie(query) do
  {:error, message} -> redirect...
  {ok, data} -> render...
end

defp get_movie(query) do
  fetch_by_id(query) 
  |> process_query query
end

defp process_query({:error, _}, query) do
  fetch_by_title(query)
end

defp process_query({:ok, data}, query), do: data

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