random-forest-cat
random-forest-cat

Reputation: 35884

Render directory contents with sinatra

I want to render the contents of a directory via sinatra's routing dsl

In my browser, I can access the folder like so:

file:///Users/lfender/source/onesearch/public/bower_components/swagger-ui/dist/

enter image description here

using sinatra routes, i'd like to point a route to this static directory:

get '/api-docs/' do
  root = File.join(settings.public_folder, 'bower_components', 'swagger-ui', 'dist')
  File.read(File.expand_path(root))
end

the above route will fail with Is a directory @ io_fread because I am passing in a directory rather than a file.

How do I read contents of static directory via sinatra route so I can serve up files in the public directory using /api-docs/? Is this possible with sinatra?

Upvotes: 0

Views: 577

Answers (2)

random-forest-cat
random-forest-cat

Reputation: 35884

Figured it out - you can serve static assets with the sinatra dsl by accepting the file path as a param:

  get '/api-docs/:path_1/:path_2' do
    path = File.join(settings.public_folder, 'bower_components', 'swagger-ui', 'dist', params[:path_1], params[:path_2])
    File.read(File.expand_path(path))
  end

  get '/api-docs/:path' do
    path = File.join(settings.public_folder, 'bower_components', 'swagger-ui', 'dist', params[:path])
    File.read(File.expand_path(path))
  end

note, you will likely have to set the appropriate mime/content types to responses

Upvotes: 0

MMeens
MMeens

Reputation: 86

Search this http://www.sinatrarb.com/intro.html for splat

get '/api-docs/*' do |sub_path|
  path = File.join(settings.public_folder, 'bower_components', 'swagger-ui', 'dist', sub_path)
  File.read(File.expand_path(path))
end

Upvotes: 2

Related Questions