-
-
Save a2ikm/5072882 to your computer and use it in GitHub Desktop.
| # 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 |
| source "https://rubygems.org" | |
| gem "sinatra" | |
| gem "tilt-jbuilder", ">= 0.4.0", :require => "sinatra/jbuilder" | |
| gem "hashie" |
| # 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 |
Now tilt-jbuilder 0.4.0 supports Sinatra.
This example is just what I needed! Thank you!
I use jruby + sinatra and did what as you said above. But got an error:
ArgumentError - wrong number of arguments calling json (0 for 1):
/home/wangxiantong/.rvm/gems/jruby-1.7.4@sinatra/gems/tilt-jbuilder-0.5.3/lib/tilt/jbuilder.rb:51:in evaluate' org/jruby/RubyKernel.java:1093:ineval'
/home/wangxiantong/.rvm/gems/jruby-1.7.4@sinatra/gems/tilt-jbuilder-0.5.3/lib/tilt/jbuilder.rb:51:in evaluate' org/jruby/RubyKernel.java:1093:ineval'
@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).
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
forked tilt-jbuilder: https://github.com/a2ikm/tilt-jbuilder/tree/sinatra-integration