Search code examples
javascriptruby-on-railssinatrapage.js

using page.js with sinatra (or rails)


I would like to know if it's possible to use page.js with sinatra. My images's route are intercepted by Sinatra instead of Page.js

get '/' do
  erb :index
end

__END__

@@ layout
 <!DOCTYPE html>
 <html lang="en">
 <head>
   <title>page.js</title>
   <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
   <script type="text/javascript" src="page.js"></script>
   <style type="text/css">ul li { display: inline; list-style:none }</style>
 </head>
 <body>
   <%= yield %>
</body>
<script type="text/javascript">
page('/images', function(ctx){
      console.log('page(' + ctx.path + ')');
          $('section#example').html('<h2 class="text-center">Listing of Images</h2>');
});
/*... /videos ..*/
page('*', function(ctx){
      console.log('page(' + ctx.path + ')');
          $('section#example').html('<h2 class="text-center">Error : ' + ctx.path + '</h2>');
});

$('document').ready(function(){page()});

</script>
</html>

@@ index
    <ul>
      <li><a href="./">index</a></li>
      <li><a href="./videos">videos</a></li>
      <li><a href="./images">images</a></li>
    </ul>
   <section id="example" class="well"></section>
   <h1>hello world</h1>

Solution

  • I think the problem is just the location of your local page.js file. Sinatra expects to find the static assets in a directory called public (otherwise the path is assumed to be a defined route). So just create the directory and move your page.js file in there (but keep the script src as is). If you want to change the directory Sinatra serves static assets from, you can do it like this:

    set :public_folder, Proc.new { File.join(root, "my_directory_with_assets") }
    

    I think you're also missing jQuery so add it from their CDN.

    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>