Skip to content

Instantly share code, notes, and snippets.

@c-spencer
Last active August 29, 2015 14:11
Show Gist options
  • Save c-spencer/13b8bcc1a8d4baf4e803 to your computer and use it in GitHub Desktop.
Save c-spencer/13b8bcc1a8d4baf4e803 to your computer and use it in GitHub Desktop.
defmodule MyApp.UserResource do
use Phoenix.Resource
defp get_user(%{"id" => id}) do
Repo.get(User, id)
end
def supported_formats do
["html", "json", "xml"]
end
def authorized?(conn, params) do
true
end
def handle_ok("json", conn, params) do
user = get_user(params)
%{
name: user.name,
email: user.email
}
end
def handle_ok("xml", conn, params) do
XMLBuilder.build(get_user params)
end
def handle_ok("html", conn, params) do
render conn, "show.html", %{user: get_user(params)}
end
end
@chrismccord
Copy link

defmodule MyApp.UserController do
  use Phoenix.Controller

  plug :accepts, ~w(html json xml)
  plug :get_user
  plug :authorize
  plug :action


  defp get_user(%Plug.Conn{params: %{"id" => id}} = conn) do
    case Repo.get(User, id) do
      {:ok, user}         -> assign(conn, :user, User.assign(user, conn.params))
      {:error, :notfound} -> conn |> send_resp(404) |> halt
    end
  end

  defp authorized(conn, _) do # authorize conn.assigns[:user]
    true
  end

  def show(conn, %{"format" => "json"}) do
    user = conn.assigns[:user]
    %{
      name: user.name,
      email: user.email
    }
  end

  def show(conn, %{"format" => "xml"} = params) do
    conn
    |> put_resp_content_type("application/xml")
    |> send_resp(:ok, XMLBuilder.build(user))
  end

  def show(conn, %{"format" => "xml"}) do
    render conn, "show.html", %{user: get_user(params)}
  end
end

@c-spencer
Copy link
Author

There's a basic implementation of this port at https://github.com/sysdea-libs/wrangle now

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