Last active
April 11, 2019 03:10
-
-
Save a2ikm/5072882 to your computer and use it in GitHub Desktop.
Use Jbuilder within Sinatra.
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
# coding: utf-8 | |
require "bundler" | |
Bundler.require | |
helpers do | |
def current_user | |
@current_user ||= | |
Hashie::Mash.new(admin?: [true, false].sample) | |
end | |
def edit_article_url(article) | |
"http://example.com/articles/#{article.id}/edit" | |
end | |
def author_url(author) | |
"http://example.com/authors/#{author.id}" | |
end | |
end | |
get '/' do | |
@article = Hashie::Mash.new(id: 1, name: "DRAGONBUSTER02", published_at:"2012-01-10") | |
@article.author = Hashie::Mash.new(id: 1, name: "Mizuhito Akiyama") | |
@article.comments = Array.new(1) { |i| Hashie::Mash.new(id: i+1, name: "@ikm", content: "My missing book...") } | |
jbuilder :index | |
end |
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
source "https://rubygems.org" | |
gem "sinatra" | |
gem "tilt-jbuilder", ">= 0.4.0", :require => "sinatra/jbuilder" | |
gem "hashie" |
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
# Place this file in the `views` directory. | |
json.(@article, :id, :name, :published_at) | |
json.edit_url edit_article_url(@article) if current_user.admin? | |
json.author do |json| | |
json.(@article.author, :id, :name) | |
json.url author_url(@article.author) | |
end | |
json.comments @article.comments do |json, comment| | |
json.(comment , :id, :name, :content) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure you're requiring
sinatra/jbuilder
. Then, inviews/index.jbuilder
things work as expected.In my example below, I'm skipping options with a
{}
and passing in local dataI learned this from the tilt docs