Search code examples
csssinatraautoprefixer

how to use rails-autoprefixer in Sinatra app?


I can't make autoprefixer work. It is called, but no result in my css code.

There are instructions for Sinatra app here - https://github.com/ai/autoprefixer-rails

application.rb

class Application < Sinatra::Base
  # Load path and gems/bundler
  $LOAD_PATH << File.expand_path(File.dirname(__FILE__))
  require "bundler"
  Bundler.require
  register Sinatra::AssetPipeline
  assets = Sprockets::Environment.new
  AutoprefixerRails.install(assets)    
  ### other

  # Actual Rails Assets integration, everything else is Sprockets
  if defined?(RailsAssets)
    RailsAssets.load_paths.each do |path|
      settings.sprockets.append_path(path)
    end
  end
end

I looked into gem source and found such examples:

@assets = Sprockets::Environment.new
@assets.append_path(@dir.join('app/app/assets/stylesheets'))
AutoprefixerRails.install(@assets, browsers: ['chrome 25'])

or

@dir = Pathname(__FILE__).dirname
@css = @dir.join('app/app/assets/stylesheets/test.css').read
AutoprefixerRails.process(@css)

Solution

  • By the looks of it, Sprockets is not configured properly. Sprockets::Enviroment takes a block, using which the paths to the assets needs to be configured. This is the folder structure I used for this example:

    ├── app.rb
    ├── assets
    │   ├── some_more_styles.css
    │   └── styles.css
    └── views
        └── index.erb
    

    Here is how I configured the Sprockets environment:

    # app.rb
    require 'autoprefixer-rails'
    
    assets = Sprockets::Environment.new do |env|
      # This ensures sprockets can find the CSS files
      env.append_path "assets"
    end
    
    AutoprefixerRails.install(assets)
    

    There's one more step to get Sprockets to work with Sinatra. Each of the assets need to be routed manually. For instance, if the index.erb has a <link> tag that tries to load a file at path /assets/styles.css, that route will result in a 404 Not Found error if it's not defined in app.rb. To avoid those 404s, define the route like so:

    # app.rb
    get '/assets/*' do
      # The env["PATH_INFO"] results in the string '/assets/styles.css' in
      # our example. We need to remove the '/assets' part since Sprockets
      # will take care of appending it when invoked on the next line.
    
      env["PATH_INFO"].sub!("/assets", "")
      assets.call(env)
    end
    

    I've uploaded the full code to https://gist.github.com/kgrz/5caf63f827e5a6181597cefae484a515 for your reference. This in turn is based on the Sinatra Recipes article on Sprockets