Sprockets and Rails3.1


rails3.1的Asset Pipeline已经用的很Cool了. `Asset Pipeline`主要是通过Sprockets提供支持.


Sprockets很简单,需要一个Sprockets Environment实例来处理所有的assets. 在Rails中就是 `YourApp::Application.assets`,在终端中输出看下:


#=>#<Sprockets::Environment:0x1c3c840 root="/xxx/xxxx/your_app", paths=["...", ...], digest="aa7d0db7619379e13b08335dee027df2">


config.assets.paths << "#{Rails.root}/foo/bar"


e = YourApp::Application.assets
asset = e['application.js']
# => #<Sprockets::BundledAsset ...>
# => The content of asset

javascript_include_tag “application”

其实就是在Sprockets Environment实例的paths中,寻找’application.js’文件,找到就返回其内容.

Sprockets Directives
  • require
  • require path inserts the contents of the asset source file specified by path. If the file is required multiple times, it will appear in the bundle only once.

  • include
  • include path works like require, but inserts the contents of the specified source file even if it has already been included or required.

  • require_directory
  • require_directory path requires all source files of the same format in the directory specified by path. Files are required in alphabetical order.

  • require_tree
  • require_tree path works like require_directory, but operates recursively to require all files in all subdirectories of the directory specified by path.

  • require_self
  • require_self tells Sprockets to insert the body of the current source file before any subsequent require or include directives.

  • depend_on
  • depend_on path declares a dependency on the given path without including it in the bundle. This is useful when you need to expire an asset’s cache in response to a change in another file.


Leave a Reply

Your email address will not be published. Required fields are marked *