Aiming study#6pdfこちらのスライドを見て、そうかRailsを使わなくてもAsset Pipelineを使うのはありだなーと思ったので、試してみました。
Rails3.1のAsset Pipelineと仲良くなる – a newcomer!
ASCIIcasts – “Episode 279 – Asset Pipelineを理解する”
アセットパイプライン(Asset Pipeline)in Ruby on Rails|シフルIT
ここを読んでだいたい理解した。
つまり、アセット系のファイルをconcatして、minifyしてくれると。
つい最近書いたCoffeeScript・Sassをgruntでコンパイルするこれと同等のことをRailsのAsset Pipelineを使ってやってみました。
Rails3.1からの機能のようですが、現時点で入れると「Rails 3.2.8」が入るので大丈夫ですね。
gem install rails
application.jsファイルを見ると分かるのですが、jquery・jquery_ujs・その他のすべてのJavaScriptファイルをひとつのapplication.jsにまとめるようです。
そこでためしに、application.jsではなく、その他にもうひとつJavaScriptファイルを作るようにしてみました。
JavaScript – CoffeeScript
ファイルの配置。
assets/javascripts ├── application.js ├── foo.coffee ├── hoge.js.coffee └── index.js
index.jsがapplication.jsと同じ役割。
中身は以下。
重要なのは、一番下の3行。
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require_self //= require hoge //= require foo
require_selfは自分自身を指しています。
あとは、個別に2個のファイルを指定、.jsは省略可能。
CSS – SCSS
同じようにCSSファイルも。
assets/stylesheets/ ├── application.css ├── index.css └── style.css.scss
index.cssがapplication.cssと同じ役割。
中身は以下。
/* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require style */
production.rbにindex.jsとindex.cssを追加する
「config/environments/production.rb」に以下のように個別でコンパイルしたいファイルを追加する。
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) config.assets.precompile += %w( index.js index.css )
コンパイルする
rake assets:precompile
上記のようにrakeすると、「public/assets」配下に出来上がる。
assets/ ├── application.css ├── application.css.gz ├── application.js ├── application.js.gz ├── index.css ├── index.css.gz ├── index.js ├── index.js.gz
こんな感じになる、余計なファイルは省略しています。
gruntでコンパイルするのもいいけど、こうゆうのもありですね。
技術評論社
売り上げランキング: 73001