简体   繁体   中英

Create basic Rake Tasks

I'm new to Ruby. I want to create simple Rake task for creating user with custom password. 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. How I can override the variable @passwd if I send CLI argument?

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\\]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM