I am quite new to Ruby as web platform and learn best by adapting and expanding examples. I like Sinatra and want to use it and Chartkick to display charts. Unfortunately, I'm having trouble getting even the most trivial example running and there seems to be a dearth of full examples (lots of 'one liners'). Here's what I have:
require 'sinatra'
require 'chartkick'
get '/' do
'<%= javascript_include_tag "//www.google.com/jsapi", "chartkick" %>
<%= pie_chart({"Football" => 10, "Basketball" => 5}) %>'
end
So what devastatingly simple thing am I doing wrong? Any help would be greatly appreciated. Thanks!
EDIT, my solution based on accepted answer:
require 'sinatra'
require 'chartkick'
template :layout do
<<LAYOUT
<html>
<head>
<title>Sinatra ERB Chartkick Test</title>
<script src="//www.google.com/jsapi"></script>
<script src="chartkick.js"></script>
</head>
<body>
<%= yield %>
</body>
</html>
LAYOUT
end
template :index do
<<INDEX
<center>
<h1>#{Time.now.inspect}</h1>
<p>
<%= pie_chart({"Football" => 10, "Basketball" => 5, "Hockey" => 2}) %>
</p>
</center>
INDEX
end
get '/' do
erb :index
end
Additionally, for the sake of newbies (like me), I put the chartkick.js file in the public folder. Also added Hockey just to make sure it wasn't magically defaulting to some canned example. And who doesn't like hockey?
This is the section of the docs you need to finish this example. If you don't want to make the views separate files, then either use inline templates, e.g.
get '/' do
erb :index
end
__END__
@@ layout
<html><body>
<%= yield %>
</html></body>
@@ index
<%= javascript_include_tag "//www.google.com/jsapi", "chartkick" %>
<%= pie_chart({"Football" => 10, "Basketball" => 5}) %>
or named templates:
template :layout do
<<LAYOUT
<html><body>
<%= yield %>
</html></body>
LAYOUT
end
template :index do
<<INDEX
<%= javascript_include_tag "//www.google.com/jsapi", "chartkick" %>
<%= pie_chart({"Football" => 10, "Basketball" => 5}) %>
INDEX
end
get '/' do
erb :index
end
I've used heredocs for convenience here, just be careful of the formatting.
来源:https://stackoverflow.com/questions/23238671/sinatra-and-chartkick-example