How to write portable image paths in CSS files for a mounted sinatra app?

112 views Asked by At

Background

You are writing a sinatra (or rack) application, and want to be able to use it, with no code changes, both as a standalone app, or as a mounted app.

That is, you might run this application on its own, or you might mount it as a sub-application inside some other app, by doing the following in your "config.ru":

run Rack::URLMap.new("/" => MainApp.new, 
                     "/my_mounted_app" => MountedApp.new)

Everything seems to be going well, since you are careful to use sinatra's url() helper in all your views, ensuring that the correct paths will be generated regardless of how or if your app is mounted.

The problem

But now you want to include an image as a background in a CSS file, and you run into a dilemma:

  1. Use the url() helper method inside your CSS file. This ensures your image paths are correct and portable, but now your CSS file has to be processed by sinatra on every request.
  2. Use a build process, perhaps involving SASS and some global config file which has the path your app is mounted to, to generate your CSS files with the correct image paths. This also ensures correct paths, but introduces the complexity of a build process.

Is there a third, better option? Is the real problem mounting an app using URLMap -- is there another way to achieve mounting which avoids these problems?

Again, the goals are:

  1. A fully portable app, which can be mounted without any changes.
  2. Static assets that don't need to be processed by sinatra.
  3. No static asset build process.
1

There are 1 answers

0
matt On BEST ANSWER

You can just use a relative URL in your CSS.

Since both the CSS and the image will be under the public dir the relative path between them will be the same wherever the app as a whole is mounted.