安装Rake
gem install rake
查看任务列表
rake -T
运行一个任务
rake task_name
指定一个文件名或才文件夹来运行任务
rake mydoc.pdf
看帮助
1 rake -h 2 rake --help
定义任务
每个任务都包含三部分内容:
- 描述(不设置,也可以,只是rake -T的时候,此任务将不会显示)
- 任务名(如果多个任务名相同,则最后一个定义的将会覆盖前面定义的)
- 任务执行代码
e.g.
1desc "One line task description" 2task :name_of_task do 3 #your code goes here 4end
任务之间的依赖
1 desc "Example of a task with prerequisites" 2 task :third_task => ["first_task", "second_task"] do 3 #Your code goes here 4 end
在third_task运行时,首先会检查first_task和second_task是否已经运行。
传参数给任务
1 desc "Example of task with parameters and prerequisites" 2 task :my_task, [:first_arg, :second_arg] => ["first_task", "second_task"] do |t, args| 3 args.with_defaults(:first_arg => "Foo", :last_arg => "Bar") 4 puts "First argument was: #{args.first_arg}" 5 puts "Second argument was: #{args.second_arg}" 6 end 7 8 rake my_task[one, two]
有时,执行rake my_task[one, two]时会报找不到该任务,这时,你需要这样执行:rake "my_task[one, two]"
参数间用逗号分隔,不能有空格
设置默认任务
1 task :default => ['my_task'] 2 3 4 task :default do 5 6 end
有以上两种方式
在其中一个任务中调用另一个任务
1desc "Example of task with invoke" 2task :first_task do 3 Rake::Task[:second_task].invoke 4end
清理任务
1 require 'rake/clean' 2 CLEAN.include('*.tmp') 3 CLOBBER.include('*.tmp','build/*')
在任务中使用其它库
1require 'erb' 2 3OUTPUT_FILE='README.html' 4TEMPLATE_FILE='template.html.erb' 5 6def get_template 7 File.read(TEMPLATE_FILE) 8end 9 10desc "Builds the HTML file, using ERB." 11file OUTPUT_FILE do 12 File.open(OUTPUT_FILE, "w+") do |f| 13 f.write(ERB.new(get_template).result()) 14 end 15end 16 17task :default => [OUTPUT_FILE]
使用shell命令
1require 'fileutils' 2 3#Stuff... 4 5task :run_command do 6 sh %{ space separated command and options } 7end
需要引入fileutils
sh方法输出:状态、运行结果
1sh %{grep pattern file} do |ok, res| 2 if ! ok 3 puts "pattern not found (status = #{res.exitstatus})" 4 end 5end
使用环境变量
1desc "Task description" 2 task :name_of_task do 3 my_setting1 = ENV['HOME'] 4 my_setting2 = ENV['MY_VAR'] 5 # Your code goes here 6end
命名空间
为了避免任务名之间的冲突。
1namespace 'build' do 2 3 # tasks... 4 5end 6 7namespace 'test' do 8 9 # tasks... 10 11 namespace 'unit' do 12 # tasks... 13 end 14 15end
使用的时候就是,rake 命名空间:命名空间:任务名
可动态定义task
1require 'yaml' 2 3# Uses FileList to get an Array of the configuration files 4CONFIG_FILES=FileList['config/*.yml'] 5 6# Returns the configuration from the file as a Hash object 7def get_config(file) 8 YAML.load_file(file) 9end 10 11CONFIG_FILES.each do |f| 12 13 config = get_config(f) 14 15 namespace config[:name] do 16 17 # Generate tasks 18 19 desc "First task for #{config[:name]}" 20 task config[:first] do 21 # Code goes here 22 end 23 24 desc "Second task for #{config[:name]}" 25 task config[:second] do 26 # Code goes here 27 end 28 29 # more... 30 31 end 32 33end
rake特定Rakefile
rake --rakefile my_task_file my_task
取消rake输出
rake --silent my_task
为任务设置特定环境亦是
rake my_task my_var1='Some value' my_var2='Another value'
调试
-
查看执行步骤,而不真正执行
rake --dry-run my_task -
日志
rake --trace my_task
资料