Mixed GUI/Command line parameters processing





5
Date Submitted Mon. Oct. 30th, 2006 2:15 AM
Revision 1 of 1
Scripter SCoon
Tags "Command Line" | GUI | Ruby | Tk
Comments 0 comments
This class illustrates mixed GUI/command line parameters passing. Any parameter may be specified in the command line. All unspecified parameters will be read using GUI dialog box.
require 'getoptlong'
require 'tk'

class DummyFtpClient

  def initialize
   
    @host = nil
    @user = nil
    @password = nil
   
    opts = GetoptLong.new(
      [ "--host",     "-h",            GetoptLong::OPTIONAL_ARGUMENT ],
      [ "--user",     "-u",            GetoptLong::OPTIONAL_ARGUMENT ],
      [ "--password", "-p",            GetoptLong::OPTIONAL_ARGUMENT ]
    )
    opts.each { |opt,arg|
      case opt
        when '--host'
          @host = arg
        when '--user'
          @user = arg
        when '--password'
          @password = arg
      end
    }

    if @host.nil? || @user.nil? || @password.nil?
      get_missed_arguments
    end
  end

  def get_missed_arguments
    root = TkRoot.new('title' => 'Connection parameters')

    hostVar = add_entry(root, 'Host:', @host)
    userVar = add_entry(root, 'User:', @user)
    passwordVar = add_entry(root, 'Password:', @password)

    onConnect = proc {
      @host = hostVar.value unless hostVar.nil?
      @user = userVar.value unless userVar.nil?
      @password = passwordVar.value unless passwordVar.nil?
      Tk.exit
    }
   
    TkButton.new(root) {
      text 'Connect'
      command onConnect
    }.pack('padx' => 10, 'pady' => 10)
    Tk.mainloop
  end

  def add_entry(root, prompt, value)
    if value.nil?
      tkVar = TkVariable.new
      tkVar.value = value
      TkLabel.new(root) {
        text prompt
        pack { padx 5; pady 5 }
      }
      TkEntry.new(root, 'textvariable' => tkVar) {
        pack { padx 5; pady 5 }
      }
      return tkVar
    else
      return nil
    end
  end

  def connect
    puts "About to connect to #{@host} as #{@user}/#{@password}"
  end
 
end

client = DummyFtpClient.new
client.connect

Vladislav Zlobin

Comments

There are currently no comments for this snippet.

Voting

Votes Down