How to use Sprockets 2 with Rails 3.0.x (how to use precompiled assets)

I am trying to replicate the basics of the resource pipeline introduced in rails 3.1 in my rails 3.0 application .

So far I have had something like this: https://gist.github.com/1112393 .

It works great:

  • I have my assets in app / assets /, lib / assets, vendor / assets ...
  • All are serviced / assets
  • I can use all stars 2 sentences, etc.

The thing is, I don’t want the rails application to serve static assets. The server must do this. This is why you can precompile assets in rails 3.1, if I understood correctly. So I did a rake task that does just that (using the Sprockets :: Environment precompilation method). And it works, I have all my assets in / public / assets /.

For example, I have

  • applications 02f8c96b342b4569513d0edf39ef55eb.css
  • application-505e8f472350fb1e0d15f6ad2f5e0389.js
  • Gallery-Icons-0e922050a85718fef3cd570df4eb5845.png

But in rails 3.1 you can do something similar in your style. css.scss.erb

background: url(<%= asset_path("gallery-icons.png") %>) 

and you will get

 background: url(/assets/gallery-icons-0e922050a85718fef3cd570df4eb5845.png) 

in a precompiled file.

The same goes for stylesheet_link_tag, javascript_link_tag, which are rewritten in rails 3.1 to add a hash if I'm not mistaken.

How can i do this?

Give me any idea you may have! Thanks.

+4
source share
2 answers

Josh answered me here: https://github.com/sstephenson/sprockets/issues/151

 Assets = Sprockets::Environment.new(Rails.root) do |env| assets = ["javascripts", "stylesheets", "images", "fonts"] paths = ["app/assets/", "lib/assets/", "vendor/assets/" ].map{|p| assets.map{|f| "#{p}#{f}" } }.flatten paths.each{ |path| env.append_path path } env.static_root = Rails.root.join("public", "assets") end 

So, basically, I have a summary task for precompiling assets:

 namespace :assets do task :precompile => :environment do Assets.precompile(*Rails.application.config.assets.precompile) end end 

My problem was mainly in knowing how to request these assets. The answer is pretty simple:

 Assets['application.js'].digest 

Having a fingerprint makes it easy to get a file name.

I created helpers to include these resources: sprockets_include_tag and sprockets_image_tag .

Done deal.

(Although right now I cannot use these helpers in my style sheets (style.css.scss.erb))

+4
source

Edit: Harry Brandage made a correspondence with my gem that uses more recent versions of everything, this is probably what you want to use:

https://github.com/hornairs/sprockets-rails

Old offer:

I made a stone that you can include in your Rails 3.0.x Gemfile, which is a Rails 3.1 integration extract:

https://github.com/jamesmacaulay/sprockets_rails3_backport

There are some differences from the behavior of Rails 3.1, but they are well documented in README. With most of the things you want to tweak, you can simply uncomment the lines I commented on.

+2
source

All Articles