cssrubyerbrackcuba

Linking a stylesheet in Ruby's Cuba framework


This seems like it should be simple, but I cannot figure out how to get link a stylesheet to an erb template in a Cuba app.

hello_world.rb

require "cuba"
require "cuba/safe"
require "cuba/render"
require "erb"

Cuba.use Rack::Session::Cookie, :secret => "__a_very_long_string__"

Cuba.plugin Cuba::Safe
Cuba.plugin Cuba::Render

Cuba.define do
  on root do
    res.write view("home")
  end
end

views/layout.erb

<!DOCTYPE html>
<html lang="en">

  <head>
    <link href="styles/basic.css" rel="stylesheet" type="text/css" />
  </head>

  <body>
    <div>
      <h1>Hello</h1>
    </div>
  </body
</html>

config.ru

require "./hello_world"
run Cuba

styles/basic.css

h1 {
   font-size: 128px;
}

div {
    padding: 50px;
    margin: 100px;
}

I have tried using some Sinatra standards like putting my css in a directory named public as well as using <link href="<%= url('styles/basic.css') %>" rel="stylesheet" type="text/css" /> but nothing has worked.


Solution

  • Cuba does not serve static assets. You can use Rack::Static for this:

    # hellow_world.rb
    Cuba.use Rack::Static,
      root: "public",
      urls: ["/javascripts", "/css", "/images"]
    

    Then, refer to this folders in your views.

    # layout.erb
    <link href="/public/css/basic.css" rel="stylesheet" type="text/css" />