[英]Create basic Rake Tasks
I'm new to Ruby. 我是Ruby的新手。 I want to create simple Rake task for creating user with custom password.
我想创建简单的Rake任务,以使用自定义密码创建用户。 I tried this code:
我尝试了这段代码:
namespace :users_create do
@passwd = 'trest333'
task create_users: :environment do
Rake::Task["create_cust:create_cust"].invoke
end
task :create_users, [:char] => :environment do |environment, args|
value = args[:char].to_s
if value.to_s.strip.length != 0
@passwd = value
Rake::Task["create_cust:create_cust"].invoke
end
end
task create_cust: :environment do
a = User.new
a.password = @passwd
a.save()
puts "password is #{@passwd}"
end
end
But when I run the code using this command rake create_cust:create_cust[some_new _pass] the sitcom password is not used. 但是,当我使用此命令rake create_cust:create_cust [some_new _pass]运行代码时,未使用情景喜剧密码。 How I can override the variable @passwd if I send CLI argument?
如果发送CLI参数,如何覆盖变量@passwd?
I think you shouldn't specify passwords on the command line as it may be saved in your session history which is a security risk. 我认为您不应该在命令行上指定密码,因为它可能会保存在会话历史记录中,这是安全隐患。 I recommend that you create a task that prompts the user for the necessary information, creates the model and reports errors, if any.
我建议您创建一个任务,以提示用户提供必要的信息,创建模型并报告错误(如果有)。 My approach looks like:
我的方法看起来像:
def prompt(message)
print(message)
STDIN.gets.chop
end
namespace :users do
task :create => :environment do
email = prompt('Email: ')
password = prompt('Password: ')
user = User.new(email: email, password: password)
unless user.save
STDERR.puts('Cannot create a new user:')
user.errors.full_messages.each do |message|
STDERR.puts(" * #{message}")
end
end
end
end
Depending on your needs, you may extend it by not prompting for arguments specified on the command line (eg email). 根据您的需要,可以通过不提示在命令行上指定的参数(例如电子邮件)来扩展它。
如果您使用zsh,则需要传递参数以执行以下任务: create_cust:create_cust\\[some_new _pass\\]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.