声明Ruby方法沿着菜单

np8igboo  于 2023-02-18  发布在  Ruby
关注(0)|答案(1)|浏览(96)

我最近一直在摆弄Ruby,所以我决定编写一个sftp客户端。

require 'net/sftp'
require 'ostruct'
require 'optparse'

class Sftp

  def parse(arguments)
    ARGV << "-h" if ARGV.empty?
    @options = OpenStruct.new

    args = OptionParser.new do |args|
      args.banner = "Usage: #{__FILE__} [options]"

      args.on("--host HOST", String,
         ) do |host|
         @options.host = host
      end

      args.on("--username USERNAME", String,
         ) do |username|
         @options.username = username
      end

      args.on("--password PASSWORD", String,
         ) do |password|
         @options.password = password
      end

      args.on("--port=PORT", Integer,
         ) do |port|
         @options.port = port
      end

      args.on("--mkdir=MAKE DIRECTORY", String,
         ) do |mkdir|
         @options.mkdir = mkdir
      end

      args.on("--rmdir=REMOVE DIRECTORY", String,
         ) do |rmdir|
         @options.rmdir = rmdir
      end

      args.on("-h", "--help", "Show help and exit") do
        puts args
        exit
      end
    end

    begin
      args.parse!(arguments)

    rescue OptionParser::MissingArgument => error
      puts "[!] ".red + error.message.bold
      exit

    rescue OptionParser::InvalidOption => error
      puts "[!] ".red + error.message.bold
      exit
    end

    def connect
      Net::SFTP.start(@options.host, @options.username, :password => @options.password, :port => @options.port) do |sftp|

        sftp.mkdir(@options.mkdir)

        puts "Creating Directory:  #{@options.mkdir}"

        sftp.rmdir(@options.rmdir)

        puts "Deleting Directory: #{@options.rmdir}"
      end
    end
  end

  def run(arguments)
    parse(arguments)
    connect
  end
end

sftp = Sftp.new
sftp.run(ARGV)

我想把这两个命令分开,例如当我传递参数mkdir时我只想运行这个命令,如果我想再次运行rmdir,我只想运行这个命令。
这和方法有关,但我找不到合适的解决方法。而且我真的很生疏。有什么建议吗?

js5cn81o

js5cn81o1#

一种非常简单的方法是在运行命令之前检查是否设置了所需的值,如果没有设置该值,则跳过该命令。

def connect
  Net::SFTP.start(@options.host, @options.username, password: @options.password, port: @options.port) do |sftp|
    if @options.mkdir
      sftp.mkdir(@options.mkdir)
      puts "Creating Directory:  #{@options.mkdir}"
    end

    if @options.rmdir
      sftp.rmdir(@options.rmdir)
      puts "Deleting Directory: #{@options.rmdir}"
    end
  end
end

相关问题