Class: Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/httping/runner.rb

Constant Summary collapse

"Usage: httping [options] uri"

Instance Method Summary collapse

Instance Method Details

#parse_argumentsObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/httping/runner.rb', line 16

def parse_arguments
  options = {
    :delay => 1,
    :format => :interactive,
    :flood => false,
    :audible => false
  }

  begin
    params = OptionParser.new do |opts|
      opts.banner = BANNER
      opts.on('-c', '--count NUM', 'Number of times to ping host') do |count|
        options[:count] = count.to_i
      end
      opts.on('-d', '--delay SECS', 'Delay in seconds between pings (default: 1)') do |delay|
        options[:delay] = delay.to_i
      end
      opts.on('-f', '--flood', 'Flood ping (no delay)') do 
        options[:flood] = true
      end
      opts.on('-j', '--json', 'Return JSON results') do 
        options[:format] = :json
      end
      opts.on('-q', '--quick', 'Ping once and return OK if up') do 
        options[:format] = :quick
      end
      opts.on('-a', '--audible', 'Beep on each ping') do 
        options[:audible] = true
      end
      opts.on('-u', '--user-agent STR', 'User agent string to send in headers') do |user_agent|
        options[:user_agent] = user_agent
      end
      opts.on('-r', '--referrer STR', 'Referrer string to send in headers') do |referrer|
        options[:referrer] = referrer
      end
      opts.on('-h', '--help', 'Display this screen') do
        puts opts
        exit
      end
      opts.parse!
      options[:uri] = parse_uri if ARGV.first
    end
  rescue OptionParser::InvalidOption => exception
    puts exception
  end
  
  if options[:format] == :json && !options.include?(:count)
    options[:count] = 5 # Default to 5 if no count provided for JSON format
  elsif options[:format] == :quick
    options[:count] = 1 # Quick format always sends only 1 ping
  end

  options
end

#parse_uriObject



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/httping/runner.rb', line 71

def parse_uri
  uri = URI.parse(ARGV.first)

  unless ["http", "https"].include?(uri.scheme) 
    puts "ERROR: Invalid URI #{uri}"
    exit
  end

  uri.path = "/" unless uri.path.match /^\//
  
  uri
end

#runObject



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/httping/runner.rb', line 4

def run
  options = parse_arguments
  
  if options[:uri]
    httping = Ping.new
    options.each { |property, value| httping.send("#{property}=", value) }
    httping.run
  else
    puts BANNER
  end
end