Rake简介及如何自定义Rake任务(rake task)

Rake是基于ruby语言的项目中用于自动化字形任务的一个友好又非常强大的工具

基于我们使用rake的目的,让我们来看一些简单的例子:

安装Rake

# 在Gemfile中添加rake
gem 'rake', '~> 10.4.2'
# 执行安装
bundle install

Rake语法

Rake任务约定如下:

desc '...'
task :name do
  # task code ...
end

如上图所示,'desc', 'name'和‘code’是主要的三个部分。虽然该脚本是ruby写的,但是文件后缀要为.rake而非.rb。

列出所有的Rake任务

列出所有可用的任务:

$ bundle exec rake -T

列出所有可用的任务以及其desc:

$ bundle exec rake -vT

小试牛刀:

定义个hello的任务去输出"Hello"

[wlin@localhost tasks]$ cat hello_world.rake 
desc 'This is my first rake task to say "hello"!'
task :hello do
  puts "Hello"
end
[wlin@localhost tasks]$ bundle exec rake hello
(in /home/wlin/ROR_Blog)
Hello
[wlin@localhost tasks]$ pwd
/home/wlin/ROR_Blog/lib/tasks
[wlin@localhost tasks]$ 

创建负责一些的rake任务

其实,rake就是可执行的ruby脚本。所以,rake可以做所以可以用ruby脚本能做的事情。

现在我们让这个task去找到所有的models并为其创建CSV文件。这些CSV文件可以用来初始化数据库。

[wlin@localhost tasks]$ cat create_csv_files_for_models.rake 
namespace :db do

  namespace :seed do

    desc "Create CSV Files for Models"
    task :create_files => :environment do
      Dir.glob("#{Rails.root}/app/models/*.rb").each { |file| require file }
      dir = "#{Rails.root}/db/csv"
      FileUtils.mkdir(dir) unless Dir.exists?(dir)
      ActiveRecord::Base.descendants.each do |model|
        unless File.exists?("#{dir}/#{model.to_s.tableize}.csv")
          csv_dir = File.dirname("#{dir}/#{model.to_s.tableize}.csv")
          FileUtils.mkdir(csv_dir) unless Dir.exists?(csv_dir)
          File.open("#{dir}/#{model.to_s.tableize}.csv", 'w+') do |f|
            f.write(model.columns.collect(&:name).join(','))
          end
          puts "CREATED FILE >> #{model.to_s.tableize}.csv"
        end
      end
    end

  end
end
[wlin@localhost tasks]$ bundle exec rake -T db
(in /home/wlin/ROR_Blog)
rake db:create              # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV it defaults...
rake db:drop                # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to dr...
rake db:fixtures:load       # Load fixtures into the current environment's database
rake db:migrate             # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status      # Display status of migrations
rake db:rollback            # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear  # Clear a db/schema_cache.dump file
rake db:schema:cache:dump   # Create a db/schema_cache.dump file
rake db:schema:dump         # Create a db/schema.rb file that is portable against any DB supported by AR
rake db:schema:load         # Load a schema.rb file into the database
rake db:seed                # Load the seed data from db/seeds.rb
rake db:seed:create_files   # Create CSV Files for Models
rake db:setup               # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the database first)
rake db:structure:dump      # Dump the database structure to db/structure.sql
rake db:structure:load      # Recreate the databases from the structure.sql file
rake db:version             # Retrieves the current schema version number
rake test:all:db            # Run tests quickly, but also reset db
rake test:db                # Run tests quickly, but also reset db

[wlin@localhost tasks]$ bundle exec rake db:seed:create_file
(in /home/wlin/ROR_Blog)
CREATED FILE >> delayed/backend/active_record/jobs.csv
CREATED FILE >> categories.csv
CREATED FILE >> posts.csv
CREATED FILE >> users.csv

其中,

  1. 'namespace'是用来对'rake'任务进行分组。在我们的代码中有两个‘namespace’,则对应的rake任务为“rake namespace1:namespace2:task_name”即'db:seed:create_file'
  2. ’=> :environment ‘不能省略。该代码用来加载当前环境,使得我们可以访问'ActiveRecord'模块
  3. ‘glob’找到指定路径中的满足格式的所有文件,并返回一个列表
  4. ‘ActiveRecord::Base.descendants’是指“ActiveRecord::Base”的所有子类,而我们定义的所有model都是“ActiveRecord::Base”的子类。

 

猜你喜欢

转载自blog.csdn.net/solinger/article/details/85560536