LoginSignup
5
0

More than 3 years have passed since last update.

10分くらいでできるRakefile入門

Posted at

対象

Makefile書ける
Rubyがインストールされてる

Rakefileとは?

Rubyで書けるMakefile

環境

ruby 2.7.1p83

Hello Rakefile!

まずは適当な作業用フォルダを作る。
ここではrakefile-sampleというフォルダ名で作る。

そこにRakefileを作成し、以下のように記述

Rakefile
task :first_task do
  puts 'Hello Rakefile!'
end

実行

rakefile-sample $ rake first_task
Hello Rakefile!

unixコマンドの実行

Rakefile
task :run_sh do
  sh %{echo Hello Rakefile sh!}
end

実行

rakefile-sample $ rake run_sh
echo Hello Rakefile sh!
Hello Rakefile sh!

instance method FileUtils#sh

複数のタスクを順番に実行

Rakefile
task :task1 do 
  puts 'task1'
end

task :task2 do 
  puts 'task2'
end

# task1, task2の後にtask3を実行
task :task3 => [:task1, :task2] do 
  puts 'task3'
end

実行

rakefile-sample $ rake task3
task1
task2
task3

ファイルを作る

taskではなくfileにすると、対象のfile(ここではGemfile)がないときだけ実行する

Rakefile
file 'Gemfile' do
  f = File.open('Gemfile', 'w')
  f.puts("source 'https://rubygems.org'")
  f.puts("gem 'rails', '~>5'")

  puts 'Gemfile created'
end

実行 (2回目は実行されないのが正)

rakefile-sample $ rake Gemfile
Gemfile created
rakefile-sample $ rake Gemfile
rakefile-sample $ 

参考

library rake
Rakeの基本的な使い方まとめ
RubyでFile(ファイル)を書き込む方法【初心者向け】

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0