Sprockets and Rails3.1

原创文章,转载请注明来源并保留原文链接

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

Sprockets

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

YourApp::Application.assets

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

可以看到这里有个paths实例变量,里面都是默认的rails的assets路径,并且这个paths可以在application.rb中配置的:

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

Sprockets::BundledAsset

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

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.

API

Leave a Reply

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