Try   HackMD

Ruby 模組化、Rake

tags: Ruby

模組化

把程式碼寫在不同檔案
require 只會載入一次
load 每次執行就載入一次

require './calculators.rb' # 引入 load './calculators.rb' # 載入
require './calculators' # 可以不用接.rb load './calculators' # X 找不到,必須明確指出完整檔名
load './calculators' load './calculators' load './calculators' require './calculators.rb' require './calculators.rb' # 無效 require './calculators.rb' # 無效

Rake

make

Rake = Ruby 版的 Make
Make 有 makefile
Rake 則是 rakefile / Rakefile

Rake Demo

Rake 定義任務

desc "mail sender" task :sendmail do puts "從資料庫取得名單..." sleep 3 puts "信件發送中..." sleep 3 puts "完成!" end
$ rake -T # rake --task rake sendmail # mail sender $ rake sendmail 從資料庫取得名單... 信件發送中... 完成!

Rake 預設任務

desc "mail sender" task :sendmail do puts "從資料庫取得名單..." sleep 3 puts "信件發送中..." sleep 3 puts "完成!" end task :default => :sendmail # 預設任務
$ rake

Rake 任務相依性

task :open_the_door do puts "開門" end task :goto_toilet => :open_the_door do # 先開門 puts "上廁所" end

$ rails db:migrate

namespace :db do desc '資料庫處理' task :migrate do puts "migration!" end end