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 |
This is great!! Is there a way of configuring the views path? I have a more pod like folder structure and would like to be able to use the view from the same folder as my route file definition.
Thanks!!!
Make sure you're requiring sinatra/jbuilder
. Then, in views/index.jbuilder
things work as expected.
In my example below, I'm skipping options with a {}
and passing in local data
require "sinatra"
require 'sinatra/jbuilder'
get '/movies/:id' do
jbuilder(:index, {}, flick: Flick.movie(params[:id]))
end
I learned this from the tilt docs
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@tomwang1013
Sorry for my late reply.
tilt-jbuilder's implementation to evaluate jbuilder expressions seems changed since v0.6.0.
So, if you're still getting same problem, you should try with its latest version (maybe v0.6.1).