天天看點

[Ruby筆記]8. Ruby Rakefile rake 删除檔案 确認filerake admin:clean_tmpreference

file

  • 目前工作目錄下,建立一個沒有任何字尾名的

    Rakefile

    檔案,目前目錄結構如下:
PS C:\Users\Administrator\RubyCode> ls


    目錄: C:\Users\Administrator\RubyCode


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         2016/5/21      0:14            tmp
-a---         2016/5/21      0:13        331 Rakefile
           
  • 然後再在目前目錄下建立一個

    tmp

    檔案夾,

    tmp

    檔案夾中任意建立若幹檔案:
PS C:\Users\Administrator\RubyCode> ls tmp


    目錄: C:\Users\Administrator\RubyCode\tmp


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本.txt
-a---         //      :           建立文本文檔.txt

           

rake admin:clean_tmp

  • Rakefile

    檔案的代碼如下:
    1. desc

      後面的是關于該檔案的描述,這裡是一個删除檔案夾下内容的

      Rakefile

    2. namespace

      後面的是

      admin

    3. task

      後面的是

      clean_tmp

    4. 最終在指令行中使用

      rake admin:clean_tmp

      來跑
namespace :admin do
  desc "Interactively delete all files in /tmp"
  task :clean_tmp do

      # task here
      Dir["./tmp/*"].each do |f|
      next unless File.file?(f)
      print "Delete #{f}? "
      answer = $stdin.gets
      case answer
      when /^y/
        File.unlink(f)
      when /^q/
        break
      end
    end

  end
end
           
  • 使用

    rake admin:clean_tmp

    指令就可以跑上面的

    Rakefile

    檔案

    接受到y就删除檔案,

    接受到q就退出操作;

PS C:\Users\Administrator\RubyCode> rake admin:clean_tmp
Delete ./tmp/建立文本文檔 - 副本 (2).txt? y
Delete ./tmp/建立文本文檔 - 副本 (3).txt? y
Delete ./tmp/建立文本文檔 - 副本 (4).txt? y
Delete ./tmp/建立文本文檔 - 副本 (5).txt? y
Delete ./tmp/建立文本文檔 - 副本 (6).txt? q

PS C:\Users\Administrator\RubyCode> ls tmp


    目錄: C:\Users\Administrator\RubyCode\tmp


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本 ().txt
-a---         //      :           建立文本文檔 - 副本.txt
-a---         //      :           建立文本文檔.txt

           

reference

《The Well-Grounded Rubyist, Second Edition》

(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)

1.4.4. The rake task-management utility

  ∧_∧
  ( ・∀・)
  ノ  つ
 (_( ノ
  しし

http://emoji.vis.ne.jp/dandy_sakano23.htm