Last active
August 29, 2015 14:17
-
-
Save jeregrine/d41bc127efb1c1935bf1 to your computer and use it in GitHub Desktop.
Encoding with Views
This file contains 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.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 |
This file contains 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.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 |
This file contains 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.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