jdesilvio
jdesilvio

Reputation: 1854

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.

Upvotes: 3

Views: 285

Answers (2)

mgiagante
mgiagante

Reputation: 41

A Cuba application is a Rack application under the (thin) hood.

A Rack application is any object that can respond to the #call method, yielding an array with a status code, a hash with headers and a body.

A Rack middleware is basically the same as an app. The only difference is the role they take in the request-response cycle:

  • An app is the final destination of the request chain and the one that will generate the original response.
  • On the other hand, a middleware is in the middle between the client and the app, pre-processing requests before they reach the app, or post-processing responses after the app generated them.

When you run your app, you run it along with a middleware stack. Each request goes from the client through the stack to your app, then its response goes from your app through the stack to the client.

Cuba doesn't implicitly add any middleware or endpoints to handle static files. This means that if a request for one is not intercepted by any middleware that can handle it and reaches your app, and then your app doesn't have a route to handle it, it will get 404'd.

As opposed to this, Sinatra does implicitly handle static file requests for you.

And that's why running

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

solves your problem, since it adds a middleware that will respond to the request generated in

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

before your app needs to.

Upvotes: 0

Uzbekjon
Uzbekjon

Reputation: 11813

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" />

Upvotes: 2

Related Questions