Class: MacWifi::Main

Inherits:
Object
  • Object
show all
Defined in:
lib/mac-wifi/main.rb

Instance Method Summary collapse

Instance Method Details

#assert_os_is_mac_osObject



12
13
14
15
16
17
# File 'lib/mac-wifi/main.rb', line 12

def assert_os_is_mac_os
  host_os = RbConfig::CONFIG["host_os"]
  unless /darwin/.match(host_os)  # e.g. "darwin16.4.0"
    raise "This program currently works only on Mac OS. Platform is '#{host_os}'."
  end
end

#callObject



61
62
63
64
65
66
67
# File 'lib/mac-wifi/main.rb', line 61

def call
  assert_os_is_mac_os

  options = parse_command_line

  MacWifi::CommandLineInterface.new(options).call
end

#parse_command_lineObject

Parses the command line with Ruby’s internal ‘optparse’. Looks for “-v” flag to set verbosity to true. optparse removes what it processes from ARGV, which simplifies our command parsing.



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
# File 'lib/mac-wifi/main.rb', line 23

def parse_command_line
  options = OpenStruct.new
  OptionParser.new do |parser|
    parser.on("-v", "--[no-]verbose", "Run verbosely") do |v|
      options.verbose = v
    end

    parser.on("-s", "--shell", "Start interactive shell") do |v|
      options.interactive_mode = true
    end

    parser.on("-o", "--output_format FORMAT", "Format output data") do |v|

      transformers = {
          'i' => ->(object) { object.inspect },
          'j' => ->(object) { JSON.pretty_generate(object) },
          'p' => ->(object) { sio = StringIO.new; sio.puts(object); sio.string },
          'y' => ->(object) { object.to_yaml }
      }

      choice = v[0].downcase

      unless transformers.keys.include?(choice)
        raise %Q{Output format "#{choice}" not in list of available formats} +
                  " (#{transformers.keys.inspect})."
      end

      options.post_processor = transformers[choice]
    end

    parser.on("-h", "--help", "Show help") do |_help_requested|
      ARGV << 'h' # pass on the request to the command processor
    end
  end.parse!
  options
end