Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use coffeescript with Sinatra

I'm trying to get coffeescript working with Sinatra. I'm new to both technologies so this is probably something silly. My problem seems to be that the coffeescript compiles to javascript but doesn't execute on page, instead appearing as html.

#sinatra app
require 'coffee-script'
get "/test.js" do
  coffee :hello
end

#hello.coffee
alert "hello world"

#My page (/test.js) doesn't execute the js - just displays the code

#On screen in the browser I get this:
   (function() {
  alert("hello world");
}).call(this);

#In the HTML I get this within the body tags

<pre style="word-wrap: break-word; white-space: pre-wrap;">(function() {
  alert('hello world!');
}).call(this);
</pre>
like image 665
Jack Kinsella Avatar asked Apr 14 '11 09:04

Jack Kinsella


1 Answers

Hmm... it looks like your example is based on this Sinatra documentation. But for some reason, Sinatra is trying to serve the .js file as HTML, and is preprocessing it accordingly. Are you by any chance setting content_type elsewhere in your application? Try changing your code to

get "/test.js" do
  content_type "text/javascript"
  coffee :hello
end

You could also try a completely different approach, using either Rack::Coffee or Barista to compile your CoffeeScript to JavaScript automatically at the Rack level. That might be easier if you have a large number of CoffeeScript files anyway.

Edit: After posting the above, it struck me that I'm probably just misinterpreting your markup. Is what you see when you load the page test.js in your browser just

alert('hello world!');

? If so, everything is working fine. JavaScript is only going to run in your browser when it's in an HTML page between <script> tags, or referenced via <script src="test.js"></script>. So in addition to your existing code, add

get "/alert", :provides => 'html' do
  '<script type=src="test.js"></script>'
end

then open that alert address in your browser, and the script should run.

like image 197
Trevor Burnham Avatar answered Nov 18 '22 10:11

Trevor Burnham