Skip to content

Commit

Permalink
Add command line interface.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexreisner committed Apr 22, 2011
1 parent e14e9b7 commit 1bd5a78
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
5 changes: 5 additions & 0 deletions bin/geocode
@@ -0,0 +1,5 @@
#!/usr/bin/env ruby

require 'geocoder/cli'

Geocoder::Cli.run ARGV
1 change: 1 addition & 0 deletions geocoder.gemspec
Expand Up @@ -12,4 +12,5 @@ Gem::Specification.new do |s|
s.description = "Provides object geocoding (by street or IP address), reverse geocoding (coordinates to street address), and distance queries for ActiveRecord and Mongoid. Designed for Rails but works with other Rack frameworks too." s.description = "Provides object geocoding (by street or IP address), reverse geocoding (coordinates to street address), and distance queries for ActiveRecord and Mongoid. Designed for Rails but works with other Rack frameworks too."
s.files = `git ls-files`.split("\n") - %w[geocoder.gemspec Gemfile init.rb] s.files = `git ls-files`.split("\n") - %w[geocoder.gemspec Gemfile init.rb]
s.require_paths = ["lib"] s.require_paths = ["lib"]
s.executables = ["geocode"]
end end
72 changes: 72 additions & 0 deletions lib/geocoder/cli.rb
@@ -0,0 +1,72 @@
require 'geocoder'
require 'optparse'

module Geocoder
class Cli

def self.run(args, out = STDOUT)
url_only = false

OptionParser.new{ |opts|
opts.banner = "Usage:\n geocode [options] location"
opts.separator "\nOptions: "

opts.on("-k <key>", "--key <key>",
"Key for geocoding API (optional for most)") do |key|
Geocoder::Configuration.api_key = key
end

opts.on("-l <language>", "--language <language>",
"Language of output (see API docs for valid choices)") do |language|
Geocoder::Configuration.language = language
end

lookups = Geocoder.valid_lookups - [:freegeoip]
opts.on("-s <service>", lookups, "--service <service>",
"Geocoding service: #{lookups.join(', ')}") do |service|
Geocoder::Configuration.lookup = service.to_sym
end

opts.on("-t <seconds>", lookups, "--timeout <seconds>",
"Maximum number of seconds to wait for API response") do |timeout|
Geocoder::Configuration.timeout = timeout.to_i
end

opts.on("-u", "--url", "Print URL for API instead of result") do
url_only = true
end

opts.on_tail("-v", "--version", "Print version number") do
puts "Geocoder #{Geocoder.version}"
exit
end

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

query = args.join(" ")

if query == ""
out << "Please specify a location to search for.\n"
exit 1
end

if url_only
out << Geocoder.send(:lookup).send(:query_url, query) + "\n"
exit 0
end

if (result = Geocoder.search(query).first)
out << result.coordinates.join(',') + "\n"
out << result.address + "\n"
exit 0
else
out << "Location '#{query}' not found.\n"
exit 2
end
end
end
end

0 comments on commit 1bd5a78

Please sign in to comment.