Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active May 12, 2017 18:48
Show Gist options
  • Save jgaskins/1ffb20cb81e0e841452a9bcaa7375140 to your computer and use it in GitHub Desktop.
Save jgaskins/1ffb20cb81e0e841452a9bcaa7375140 to your computer and use it in GitHub Desktop.
jbuilder vs non-jbuilder examples
# app/controllers/messages_controller.rb
class MessagesController < ApplicationController
def show
message = Message.find(params[:id])
respond_to do |format|
format.json { render :show, locals: { message: message } }
end
end
end
# app/views/messages/show.json.jbuilder
json.content format_content(message.content)
json.(message, :created_at, :updated_at)
json.author do
json.name message.creator.name.familiar
json.email_address message.creator.email_address_with_name
json.url url_for(message.creator, format: :json)
end
if current_user.admin?
json.visitors calculate_visitors(message)
end
json.comments message.comments, :content, :created_at
json.attachments message.attachments do |attachment|
json.filename attachment.filename
json.url url_for(attachment)
end
# app/controllers/messages_controller.rb
class MessagesController < ApplicationController
def show
message = Message.find(params[:id])
render json: message_response(message)
end
def message_response(message)
{
content: format_content(message.content),
created_at: message.created_at,
updated_at: message.updated_at,
# or, if you like the metaprogramming from the jbuilder example:
# %I(created_at updated_at).map { |msg| @message.public_send(msg) },
author: {
name: message.creator.name.familiar,
email_address: message.creator.email_address_with_name,
url: url_for(message.creator, format: :json),
},
comments: message.comments.map { |comment|
{
content: comment.content,
created_at: comment.created_at,
}
},
attachments: message.attachments.map { |attachment|
{
filename: attachment.filename,
url: attachment_url(attachment),
}
},
}.tap do |hash|
# All conditional logic would go here
if current_user.admin?
hash[:visitors] = calculate_visitors(message)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment