Skip to content

Instantly share code, notes, and snippets.

@chrismccord
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismccord/86b02961af24f227bf33 to your computer and use it in GitHub Desktop.
Save chrismccord/86b02961af24f227bf33 to your computer and use it in GitHub Desktop.
JSON only Phoenix view
defmodule MyApp.UserController do
use Phoenix.Controller
def show(conn, %{"id" => id}) do
render conn, "show", user: Repo.get!(user, id)
end
def index(conn, _) do
render conn, "index", users: Repo.all(User)
end
end
defmodule MyApp.UserView do
use MyApp.View
def render("show.json", %{user: user}) do
user |> to_map
end
def render("index.json", %{users: users}) do
users |> Enum.map(&to_map(&1))
end
defp to_map(user = %User{}) do
%{
id: user.id,
name: user.name,
age: user.age
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment