user1297102
user1297102

Reputation: 661

Error listing files in a directory with Sinatra

I'm trying to follow along with this Sinatra tutorial (from 2008):
http://devver.wordpress.com/2008/11/25/building-a-iphone-web-app-in-under-50-lines-with-sinatra-and-iui/

But ran into some problems with the code, for me the files aren't listed under the main heading currently. When I change dir to "./public/files/" the list is shown, but clicking a file's link results in an error page ("Sinatra doesn't know this ditty"). If I remove the public from the URL it will in this case work. How can I resolve the two?

Also, I get an error if with the line "use_in_file_template!", which I just comment out. And I'm not familiar with CSS, so could someone tell me where I can the color of the text?


require 'rubygems'
require 'sinatra'
require 'pathname'

get "/" do
  dir = "./files/"
  @links = Dir[dir+"*"].map { |file|
    file_link(file)
  }.join
  erb :index
end

helpers do

  def file_link(file)
    filename = Pathname.new(file).basename
    "<li><a href='#{file}' target='_self'>#{filename}</a></li>"
  end

end

use_in_file_templates!

__END__

@@ index
<html>
  <head>
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
    <style type="text/css" media="screen">@import "/stylesheets/iui.css";</style>
    <script type="application/x-javascript" src="/javascripts/iui.js"></script>
  </head>

  <body>
    <div class="toolbar">
    <h1 id="pageTitle"></h1>
    </div>
    <ul id="home" title="Your files, sir." selected="true">
       <%= @links %>
    </ul>
  </body>

</html>

Upvotes: 1

Views: 231

Answers (1)

Yevgeniy Anfilofyev
Yevgeniy Anfilofyev

Reputation: 4847

Well, sinatra (as many other web servers) assumes that public is a root directory for static files and it just does not use it when accessing files/dirs in it. So, in your case, you could change (add public to path when get list of files and remove it when generate links to them) some lines in your code:

get "/" do
  dir = "public/files/"
  @links = Dir[dir+"*"].map { |file|
    file_link(file)
  }.join
  erb :index
end

helpers do
  def file_link(file)
    filename = Pathname.new(file).basename
    "<li><a href='#{file.sub('public','')}' target='_self'>#{filename}</a></li>"
  end
end

Upvotes: 2

Related Questions