Search code examples
csssinatra

Updated - Sinatra doesn't recognize any route


I have a Sinatra 4 app, and I'm trying to load a CSS file. I have placed it in /public/application.css and in my view's header I have added <link rel="stylesheet" type="text/css" href="/application.css"> but the file is not found.

When I try to point my browser to http://localhost:9292/assets/stylesheets/application.css, I get the "Sinatra doesn’t know this ditty." page.

Update: After some troubleshooting, I noticed that if I start the app with ruby application.rb Sinatra starts (Sinatra (v4.0.0) has taken the stage on 4567 for development with backup from Puma), but no page is displayed. When I point my browser to http://localhost:4567, I get the "Sinatra doesn’t know this ditty." page.

What am I missing here? Why isn't Sinatra working?

Here my code.

# config.ru
require File.dirname(__FILE__) + "/application.rb"

run ABC
# application.rb
require "sinatra"

class ABC < Sinatra::Base
  set :views, Proc.new { File.join(root, "app", "views") }

  get "/" do
    erb :index
  end
end

# app/views/index.erb
<h1>ABC</h1>

Solution

  • You are mixing up the classic and modular style Sinatra apps.

    In order to use the modular style, replace

    require 'sinatra'
    

    with

    require 'sinatra/base'
    

    This will then work with your config.ru. If you want to be able to run your app with ruby application.rb then you can add something like this to the end of application.rb:

    if $0 == __FILE__
      ABC.run!
    end
    

    This checks if the current file is the file used to start the program, and if it is so then start the built in server running your app.

    When you use require 'sinatra', Sinatra is set up to use the classic style. Here it expects routes to be defined at the top level, and they are added to the Sinatra::Application app. It is this app, not your ABC app, that is run when you do ruby application.rb. Since there are no routes defined on this app you will just get 404 for any url.