- 追加された行はこの色です。
- 削除された行はこの色です。
&tag(Rails/バッチ処理);
*目次 [#p4b04cd2]
#contents
*関連ページ [#k5d005dc]
-[[Rails]]
*参考情報 [#b4238e61]
*基本 [#d2990786]
-lib/tasksの下にファイルを作成し、バッチ処理的な事を行わせる。
-rails runnerで実行する。
*作成 [#p7ca8fc4]
-config/application.rbを編集し、autoload_pathsを設定しておく
config.autoload_paths += %W(#{config.root}/lib) # 追加
-lib/tasks/hello_task.rbを作成する
#pre{{
class Tasks::HelloTask
def self.execute
print "Hello World!! env=#{Rails.env}\n"
end
end
}}
-実行する
bundle exec rails runner "Tasks::HelloTask.execute"
*パラメータを渡したい [#na9d04b7]
**方法1: パラメータを直接渡す [#dee93375]
-呼び出し側のシェルスクリプト。hello.shとして保存。引数をクォートして渡す(a b c => 'a', 'b', 'c')
#pre{{
#!/bin/sh
str=""
for var in $*
do
if [ "$str" = "" ]; then
str="'${var}'"
else
str="${str}, '${var}'"
fi
done
bundle exec rails runner "Tasks::HelloTask.execute($str)"
}}
-タスク
#pre{{
class Tasks::HelloTask
def self.execute(*params)
print "Hello World!! env=#{Rails.env}\n"
p params
end
end
}}
-実行
#pre{{
$ ./hello.sh a b c
Hello World!! env=development
["a", "b", "c"]
}}
**方法2: runnerでスクリプトを呼び出す [#s7819bd9]
-runnerにはRubyのコードを文字列として渡せるほかスクリプトを渡すこともできる。
-[[rails runnerで起動するスクリプトにオプションを渡す - Qiita:http://qiita.com/yoppi/items/c6dbc0326b1aa2902ef0]]
-呼び出し側のシェルスクリプト hello_parameter.shとして保存。
#pre{{
#!/bin/sh
bundle exec rails runner lib/tasks/hello_task.rb a b c
}}
-タスク
#pre{{
class Tasks::HelloTask
def self.execute(*params)
print "Hello World!! env=#{Rails.env}\n"
p params
end
end
if $0 == __FILE__
Tasks::HelloTask.execute(*ARGV)
end
}}
-実行
#pre{{
./hello_parameter.sh
Hello World!! env=development
["a", "b", "c"]
}}