Last active
August 29, 2015 14:05
-
-
Save chrismccord/86b02961af24f227bf33 to your computer and use it in GitHub Desktop.
JSON only Phoenix view
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 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