本文介绍了如何将参数传递给具有 Rails 环境的 Rake 任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以按如下方式传递参数:
desc "测试参数"任务: :hello, :user, :message do |t, args|args.with_defaults(:message => "感谢您登录")puts "你好 #{args[:user]}.#{:message}"结尾
我还可以为 Rails 应用程序加载当前环境
desc "测试环境"任务::你好=>:环境做输入你好#{User.first.name}."结尾
我想做的是能够拥有变量和环境
desc "测试环境和变量"任务::你好=>:environment, :message do |t, args|args.with_defaults(:message => "感谢您登录")把你好#{User.first.name}.#{:message}"结尾
但这不是有效的任务调用.有谁知道我如何实现这一目标?
解决方案
TLDR;
task :t, [args] =>[deps]
原答案
当您将参数传递给 rake 任务时,您可以使用 :needs 选项来要求环境.例如:
desc "测试环境和变量"任务 :hello, :message, :needs => :environment do |t, args|args.with_defaults(:message => "感谢您登录")把你好#{User.first.name}.#{args.message}"结尾根据@Peiniau 在下面的评论更新
至于 Rails > 3.1
task :t, arg, :needs =>[deps] # 已弃用
请使用
task :t, [args] =>[deps]
I am able to pass in arguments as follows:
desc "Testing args"
task: :hello, :user, :message do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{args[:user]}. #{:message}"
end
I am also able to load the current environment for a Rails application
desc "Testing environment"
task: :hello => :environment do
puts "Hello #{User.first.name}."
end
What I would like to do is be able to have variables and environment
desc "Testing environment and variables"
task: :hello => :environment, :message do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{User.first.name}. #{:message}"
end
But that is not a valid task call. Does anyone know how I can achieve this?
解决方案
TLDR;
task :t, [args] => [deps]
Original Answer
When you pass in arguments to rake tasks, you can require the environment using the :needs option. For example:
desc "Testing environment and variables"
task :hello, :message, :needs => :environment do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{User.first.name}. #{args.message}"
end
Updated per @Peiniau's comment below
As for Rails > 3.1
task :t, arg, :needs => [deps] # deprecated
Please use
task :t, [args] => [deps]
这篇关于如何将参数传递给具有 Rails 环境的 Rake 任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!