経緯
現在 PHP で開発を行っているのですが、ローカルでのテスト自動実行やファイルの同期は Guard を利用しています。
その工程の中で、Guard 起動時に一度ローカル環境からVM上へrsyncで同期を取りたくなったので、その方法記述します。
ソース
require 'guard/guard'
notification :growl
module ::Guard
# 起動時に同期を行う Guard のプラグイン
class SyncronizeAll < Guard
def start
hostname="172.0.0.1"
username="eccyan"
application_path="/home/eccyan/devel/project/web"
current_path="/var/www/project/current"
# 同期を実行する
puts "Starting syncronize all to #{hostname}"
if result = `rsync -rvz --delete --omit-dir-times \
'#{application_path}/' '#{username}@#{hostname}':'#{current_path}'`
if $?.success?
::Guard::Notifier.notify("Syncronized", :title => 'Syncronize All')
else
::Guard::Notifier.notify("Failed", :title => 'Syncronize All',
:image => :failed)
end
end
# start は処理の成否を返さなければならない
$?.success?
end
end
end
group :your_group do
# 作成したプラグインを定義しておけば、初回起動時に実行される
guard :syncronize_all
end
解説
まず、Guard からイベントとして呼ばれるメソッドは以下のものしかありません
start
stop
reload
run_all
def run_on_changes(paths)
run_on_additions(paths)
run_on_modifications(paths)
run_on_removals(paths)
この中の start
メソッドが Guard 起動時に呼ばれるので、ここへ処理を書きます。
しかし、 __いちいちプラグインを作るのは面倒くさい__ため Guardfile 内にインラインで記述しています。
これなら気軽にローカル環境が構築できますね。
Ruby 最高!Ruby イエス!
参考