# Rails應用模版
應用模版是一個包括使用DSL添加gems/initializers等操作的普通Ruby文件.可以很方便的在你的應用中創建。
讀完本章節,你將會學到:
* 如何使用模版生成/個性化一個應用。
* 如何使用Rails的模版API編寫可復用的應用模版。
### Chapters
1. [模版應用簡介](#%E6%A8%A1%E7%89%88%E5%BA%94%E7%94%A8%E7%AE%80%E4%BB%8B)
2. [模版API](#%E6%A8%A1%E7%89%88api)
* [gem(*args)](#gem(*args))
* [gem_group(*names, &block)](#gem_group(*names,-&block))
* [add_source(source, options = {})](#add_source(source,-options-=-%7B%7D))
* [environment/application(data=nil, options={}, &block)](#environment/application(data=nil,-options=%7B%7D,-&block))
* [vendor/lib/file/initializer(filename, data = nil, &block)](#vendor/lib/file/initializer(filename,-data-=-nil,-&block))
* [rakefile(filename, data = nil, &block)](#rakefile(filename,-data-=-nil,-&block))
* [generate(what, *args)](#generate(what,-*args))
* [run(command)](#run(command))
* [rake(command, options = {})](#rake(command,-options-=-%7B%7D))
* [route(routing_code)](#route(routing_code))
* [inside(dir)](#inside(dir))
* [ask(question)](#ask(question))
* [yes?(question) or no?(question)](#yes-questionmark(question)-or-no-questionmark(question))
* [git(:command)](#git(:command))
3. [高級應用](#%E9%AB%98%E7%BA%A7%E5%BA%94%E7%94%A8)
### 1 模版應用簡介
為了使用一個模版,你需要為Rails應用生成器在生成新應用時提供一個'-m'選項來配置模版的路徑。該路徑可以是本地文件路徑也可以是URL地址。
```
$ rails new blog -m ~/template.rb
$ rails new blog -m http://example.com/template.rb
```
你可以使用rake的任務命令`rails:template`為Rails應用配置模版。模版的文件路徑需要通過名為'LOCATION'的環境變量設定。再次強調,這個路徑可以是本地文件路徑也可以是URL地址:
```
$ bin/rake rails:template LOCATION=~/template.rb
$ bin/rake rails:template LOCATION=http://example.com/template.rb
```
### 2 模版API
Rails模版API很容易理解,下面我們來看一個典型的模版例子:
```
# template.rb
generate(:scaffold, "person name:string")
route "root to: 'people#index'"
rake("db:migrate")
git :init
git add: "."
git commit: %Q{ -m 'Initial commit' }
```
下面的章節將詳細介紹模版API的主要方法:
#### 2.1 gem(*args)
向一個Rails應用的`Gemfile`配置文件添加一個'gem'實體。 舉個例子,如果你的應用的依賴項包含`bj` 和 `nokogiri`等gem :
```
gem "bj"
gem "nokogiri"
```
需要注意的是上述代碼不會安裝gem文件到你的應用里,你需要運行`bundle install` 命令來安裝它們。
```
bundle install
```
#### 2.2 gem_group(*names, &block)
將gem實體嵌套在一個組里。
比如,如果你只希望在`development`和`test`組里面使用`rspec-rails`,可以這么做 :
```
gem_group :development, :test do
gem "rspec-rails"
end
```
#### 2.3 add_source(source, options = {})
為Rails應用的`Gemfile`文件指定數據源。
舉個例子。如果你需要從`"http://code.whytheluckystiff.net"`下載一個gem:
```
add_source "http://code.whytheluckystiff.net"
```
#### 2.4 environment/application(data=nil, options={}, &block)
為`Application`在`config/application.rb`中添加一行內容。
如果聲明了`options[:env]`參數,那么這一行會在`config/environments`添加。
```
environment 'config.action_mailer.default_url_options = {host: "http://yourwebsite.example.com"}', env: 'production'
```
可以使用一個 'block'標志代替`data`參數。
#### 2.5 vendor/lib/file/initializer(filename, data = nil, &block)
為一個應用的`config/initializers`目錄添加初始化器。
假如你喜歡使用`Object#not_nil?` 和 `Object#not_blank?`:
```
initializer 'bloatlol.rb', <<-CODE
class Object
def not_nil?
!nil?
end
def not_blank?
!blank?
end
end
CODE
```
一般來說,`lib()`方法會在 `lib/` 目錄下創建一個文件,而`vendor()`方法會在`vendor/`目錄下創建一個文件。
甚至可以用`Rails.root`的`file()`方法創建所有Rails應用必須的文件和目錄。
```
file 'app/components/foo.rb', <<-CODE
class Foo
end
CODE
```
上述操作會在`app/components`目錄下創建一個 `foo.rb` 文件。
#### 2.6 rakefile(filename, data = nil, &block)
在 `lib/tasks`目錄下創建一個新的rake文件執行任務:
```
rakefile("bootstrap.rake") do
<<-TASK
namespace :boot do
task :strap do
puts "i like boots!"
end
end
TASK
end
```
上述代碼將在`lib/tasks/bootstrap.rake`中創建一個`boot:strap`任務。
#### 2.7 generate(what, *args)
通過給定參數執行生成器操作:
```
generate(:scaffold, "person", "name:string", "address:text", "age:number")
```
#### 2.8 run(command)
執行命令行命令,和你在命令行終端敲命令效果一樣。比如你想刪除`README.rdoc`文件:
```
run "rm README.rdoc"
```
#### 2.9 rake(command, options = {})
執行Rails應用的rake任務,比如你想遷移數據庫:
```
rake "db:migrate"
```
你也可以在不同的Rails應用環境中執行rake任務:
```
rake "db:migrate", env: 'production'
```
#### 2.10 route(routing_code)
在`config/routes.rb`文件中添加一個路徑實體。比如我們之前為某個人生成了一些簡單的頁面并且把 `README.rdoc`刪除了。現在我們可以把應用的`PeopleController#index`設置為默認頁面:
```
route "root to: 'person#index'"
```
#### 2.11 inside(dir)
允許你在指定目錄執行命令。舉個例子,你如果希望將一個外部應用添加到你的新應用中,可以這么做:
```
inside('vendor') do
run "ln -s ~/commit-rails/rails rails"
end
```
#### 2.12 ask(question)
`ask()`方法為你提供了一個機會去獲取用戶反饋。比如你希望用戶在你的新應用'shiny library'提交用戶反饋意見:
```
lib_name = ask("What do you want to call the shiny library ?")
lib_name << ".rb" unless lib_name.index(".rb")
lib lib_name, <<-CODE
class Shiny
end
CODE
```
#### 2.13 yes?(question) or no?(question)
這些方法是根據用戶的選擇之后做一些操作的。比如你的用戶希望停止Rails應用,你可以這么做:
```
rake("rails:freeze:gems") if yes?("Freeze rails gems?")
# no?(question) acts just the opposite.
```
#### 2.14 git(:command)
Rails模版允許你運行任何git命令:
```
git :init
git add: "."
git commit: "-a -m 'Initial commit'"
```
### 3 高級應用
應用模版是在`Rails::Generators::AppGenerator`實例的上下文環境中執行的,它使用`apply` 動作來執行操作[Thor](https://github.com/erikhuda/thor/blob/master/lib/thor/actions.rb#L207)。這意味著你可以根據需要擴展它的功能。
比如重載`source_paths`方法實現把本地路徑添加到你的模版應用中。那么類似`copy_file`方法會在你的模版路徑中識別相對路徑參數。
```
def source_paths
[File.expand_path(File.dirname(__FILE__))]
end
```
### 反饋
歡迎幫忙改善指南質量。
如發現任何錯誤,歡迎修正。開始貢獻前,可先行閱讀[貢獻指南:文檔](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation)。
翻譯如有錯誤,深感抱歉,歡迎 [Fork](https://github.com/ruby-china/guides/fork) 修正,或至此處[回報](https://github.com/ruby-china/guides/issues/new)。
文章可能有未完成或過時的內容。請先檢查 [Edge Guides](http://edgeguides.rubyonrails.org) 來確定問題在 master 是否已經修掉了。再上 master 補上缺少的文件。內容參考 [Ruby on Rails 指南準則](ruby_on_rails_guides_guidelines.html)來了解行文風格。
最后,任何關于 Ruby on Rails 文檔的討論,歡迎到 [rubyonrails-docs 郵件群組](http://groups.google.com/group/rubyonrails-docs)。
- Ruby on Rails 指南 (651bba1)
- 入門
- Rails 入門
- 模型
- Active Record 基礎
- Active Record 數據庫遷移
- Active Record 數據驗證
- Active Record 回調
- Active Record 關聯
- Active Record 查詢
- 視圖
- Action View 基礎
- Rails 布局和視圖渲染
- 表單幫助方法
- 控制器
- Action Controller 簡介
- Rails 路由全解
- 深入
- Active Support 核心擴展
- Rails 國際化 API
- Action Mailer 基礎
- Active Job 基礎
- Rails 程序測試指南
- Rails 安全指南
- 調試 Rails 程序
- 設置 Rails 程序
- Rails 命令行
- Rails 緩存簡介
- Asset Pipeline
- 在 Rails 中使用 JavaScript
- 引擎入門
- Rails 應用的初始化過程
- Autoloading and Reloading Constants
- 擴展 Rails
- Rails 插件入門
- Rails on Rack
- 個性化Rails生成器與模板
- Rails應用模版
- 貢獻 Ruby on Rails
- Contributing to Ruby on Rails
- API Documentation Guidelines
- Ruby on Rails Guides Guidelines
- Ruby on Rails 維護方針
- 發布記
- A Guide for Upgrading Ruby on Rails
- Ruby on Rails 4.2 發布記
- Ruby on Rails 4.1 發布記
- Ruby on Rails 4.0 Release Notes
- Ruby on Rails 3.2 Release Notes
- Ruby on Rails 3.1 Release Notes
- Ruby on Rails 3.0 Release Notes
- Ruby on Rails 2.3 Release Notes
- Ruby on Rails 2.2 Release Notes