7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rakeタスクに可変長の引数を渡す

Last updated at Posted at 2017-01-27

##よくある引数ありのrakeタスク
% rails g task task_nameでタスク生成

namespace :task_name do
  desc "実行処理の説明"
  task :create, ['hoge', 'fuga'] => :environment do |task, args|
    p task
    p args
  end
end

###実行

% rake 'task_name:create[foo, bar]'

# 実行結果

<Rake::Task task_name:create => [environment]>
{:hoge=>"foo", :fuga=>"bar"}

この受け取り方だとargsは予め指定した形のHashになるので、可変長は渡しづらい

対策

ARGVから引数を受け取る

namespace :task_name do
  desc "実行処理の説明"
  task create: :environment do |task|
    p ARGV
    p task.name
    # sliceしたいけどARGVはfrozenなのでdup
    copy = ARGV.first.dup
    copy.slice!(task.name)

    #配列っぽい文字列("[foo,bar]")が出来るので配列にする
    args = YAML.load(copy)
    p args
  end
end

実行

% bundle exec rake 'task_name:create[foo,bar]'

# 実行結果

["task_name:create[foo,bar]"]
"task_name:create"
["foo", "bar"] #=>Array

ひとまず満足

7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?