Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra app with sprockets not working on Heroku

I have a little Sinatra app including this module:

module Sprockets
  module Helpers
    def asset_path(source)
      "/assets/#{Environment.instance.find_asset(source).digest_path}"
    end

    def sprockets
      Environment.instance.call(env)
    end
  end

  class << self
    def precompile
      dir = 'public/assets'

      FileUtils.rm_rf(dir, secure: true)
      ::Sprockets::StaticCompiler.new(Environment.instance, 'public/assets', [/\.(png|jpg)$/, /^(application|ie)\.(css|js)$/]).compile
    end
  end

  class Environment < ::Sprockets::Environment
    include Singleton

    def initialize
      super
      %w[app lib vendor].each do |dir|
        %w[images javascripts stylesheets].each do |type|
          path = File.join(root, dir, 'assets', type)
          append_path(path) if File.exist?(path)
        end
      end

      js_compressor = Uglifier.new
      css_compressor = YUI::CssCompressor.new

      context_class.instance_eval do
        include Helpers
      end
    end
  end
end

and with following route defined:

get('/assets/*') do
  sprockets # Defined in the module above
end

Everything works just great, assets are loaded and displayed properly on my local machine using pow. But on Heroku no single asset is loaded, the server just returns 404 for every asset file.

like image 953
Mario Uher Avatar asked Nov 08 '11 18:11

Mario Uher


1 Answers

Simplified the module and now it works! Weird...

class Assets < Sprockets::Environment
  class << self
    def instance(root = nil)
      @instance ||= new(root)
    end
  end

  def initialize(root)
    super

    %w[app lib vendor].each do |dir|
      %w[images javascripts stylesheets].each do |type|
        path = File.join(root, dir, 'assets', type)
        self.append_path(path) if File.exist?(path)
      end
    end

    self.css_compressor = YUI::CssCompressor.new
    self.js_compressor = Uglifier.new

    context_class.instance_eval do
      include Helpers
    end
  end

  def precompile
    dir = 'public/assets'

    FileUtils.rm_rf(dir, secure: true)
    Sprockets::StaticCompiler.new(self, 'public/assets', ['*']).compile
  end

  module Helpers
    def asset_path(source)
      "/assets/#{Assets.instance.find_asset(source).digest_path}"
    end
  end
end
like image 195
Mario Uher Avatar answered Sep 24 '22 11:09

Mario Uher