Rails3.1でController毎に異なるJavaScriptを出力
Rails3.1から組み込まれたCoffeeScriptを検証しています。コントローラを作成するとapp/assets/javascriptsにコントローラー名.js.coffeeってファイルが作成されますよね。当然該当するコントローラーに関係するViewを表示した時だけロードされると思ってたんだけど、全てのスクリプトがまとめてロードされてしまうみたいです。
これは次のようにmanifest fileを変更すると動作を変えることができます。
app/assets/javascipts/application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree . (この行を削除する)
app/views/layouts/application.html.erb
<%= javascript_include_tag "application" %> <%= javascript_include_tag params[:controller] %> (この行を追加する)
これで、コントローラーに対応するCoffeeScriptが読み込まれるようになりました。
SCSSも同じようにマニフェストファイルを変更することで切り替えることができますよ。
今回Rails GuidesのAsset Pipelineのページを読んだのですが、Rails3.1を使うのならばひと通り目を通しておいたほうがよさそうです。