开发者

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

I'm trying to replicate the basics of the asset pipeline introduced in rails 3.1 in my rails 3.0 app.

So far, I've got something like this: https://gist.github.com/1112393.

It works great:

  • I have my assets in app/assets/, lib/assets, vendor/assets...
  • They're all served at /assets
  • I can use everything sprockets 2 offers etc...

The thing is, I don't want the rails app to serve static assets. The server should do it. T开发者_高级运维hat's why you can precompile assets in rails 3.1, if I understood correctly. So I've made a rake task that does just that (using the precompile method of Sprockets::Environment). And it works, I have all my assets at /public/assets/.

For instance, I have

  • application-02f8c96b342b4569513d0edf39ef55eb.css
  • application-505e8f472350fb1e0d15f6ad2f5e0389.js
  • gallery-icons-0e922050a85718fef3cd570df4eb5845.png

But in rails 3.1, you can do something like that in your style.css.scss.erb

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

and you'd get

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

in the precompiled file.

Same for stylesheet_link_tag, javascript_link_tag which are overwritten in rails 3.1 to add the hash, if I'm not mistaken.

How can I do this?

Give me every idea you can have! Thanks.


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 rake task to precompile the assets:

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

My problem was mainly to know how to request these assets. The answer is quite simple:

Assets['application.js'].digest

Having the fingerprint, it's easy to get the filename.

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

Done deal.

(Although right now, I can't use these helpers in my stylesheets (style.css.scss.erb))


Edit: Harry Brundage did a rewrite of my gem which uses more recent versions of everything, it's probably what you want to use:

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

Old suggestion:

I've made a gem you can include in your Rails 3.0.x Gemfile which is an extraction of the Rails 3.1 sprockets integration:

https://github.com/jamesmacaulay/sprockets_rails3_backport

There are some differences from the Rails 3.1 behaviour, but they are well documented in the README. With most of the stuff you'd want to tweak, you can just uncomment the lines I've commented out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜