Skip to content

Instantly share code, notes, and snippets.

@jeregrine
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeregrine/d41bc127efb1c1935bf1 to your computer and use it in GitHub Desktop.
Save jeregrine/d41bc127efb1c1935bf1 to your computer and use it in GitHub Desktop.
Encoding with Views
defmodule MyApp.CommentView do
use MyApp.Web, :view
@attributes ~W(id name inserted_at)
def render("show.json", data: data) when is_list(data) do
for c <- data do
render("show.json", data: data)
end
end
def render("show.json", data: data) do
data
|> Map.take(@attributes)
|> Map.put(:user, UserView.render('show_lite.json', data: data.user))
end
end
defmodule MyApp.MyModelView do
use MyApp.Web, :view
@attributes ~W(id body title inserted_at)
def render("show.json", data: data)
data
|> Map.take(@attributes)
|> Map.update!(:title, &String.capitalize)
|> Map.put(:user, UserView.render("show.json", data: data.user)
|> Map.put(:comments, CommentView.render("show.json", data: data.comments))
end
end
defmodule MyApp.UserView do
use MyApp.Web, :view
@attributes ~W(id name inserted_at)
def render("show.json", data: data)
render("show_lite.json", data: data)
|> Map.put(:image, ImageView.render("show.json", data: data.image))
end
def render("show_lite.json", data: data)
data
|> Map.take(@attributes)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment