Class: Graticule::Cli

Inherits:
Object
  • Object
show all
Defined in:
lib/graticule/cli.rb

Overview

A command line interface for geocoding. From the command line, run:

geocode 49423

Outputs:

# Holland, MI 49423 US
# latitude: 42.7654, longitude: -86.1085

Usage: geocode [options] location

Options:

-s, --service service            Geocoding service
-a, --apikey apikey              API key for the selected service
-h, --help                       Help

Class Method Summary collapse

Class Method Details

.start(args, out = STDOUT) ⇒ Object


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
# File 'lib/graticule/cli.rb', line 24

def self.start(args, out = STDOUT)
  options = { :service => :yahoo, :api_key => 'YahooDemo' }
  supported_services = %w(yahoo google yandex geocoder_us metacarta)

  OptionParser.new do |opts|
    opts.banner = "Usage: geocode [options] location"
    opts.separator ""
    opts.separator "Options: "

    opts.on("-s service", supported_services, "--service service",
            "Geocoding service.", "Currently supported services: #{supported_services.join(", ")}") do |service|
      options[:service] = service
    end

    opts.on("-a apikey", "--apikey apikey", "API key for the selected service") do |apikey|
      options[:api_key] = apikey
    end

    opts.on_tail("-h", "--help", "Help") do
      puts opts
      exit
    end
  end.parse! args

  options[:location] = args.join(" ")

  result = Graticule.service(options[:service]).new(*options[:api_key].split(',')).locate(options[:location])
  location = (result.is_a?(Array) ? result.first : result)
  if location
    out << location.to_s(:coordinates => true) + "\n"
    exit 0
  else
    out << "Location not found"
    exit 1
  end
rescue Graticule::CredentialsError
  $stderr.puts "Invalid API key. Pass your #{options[:service]} API key using the -a option. "
rescue OptionParser::InvalidArgument, OptionParser::InvalidOption,
    Graticule::Error => error
  $stderr.puts error.message
end