Created
October 20, 2016 19:24
-
-
Save Griminy/b6b0b83fed278defcf2e9b5db2201116 to your computer and use it in GitHub Desktop.
get local or some city's time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'gserver' | |
require 'socket' | |
require 'google_timezone' | |
require 'geokit' | |
require 'timezone' | |
class TimeServer < GServer | |
def initialize(port=3000, *args) | |
super(port, *args) | |
end | |
def serve(io) | |
begin | |
io.puts "Hey, dude, which city's time you want to know?" | |
line = io.gets | |
if line =~ /time/ | |
io.puts "----------------------------" | |
io.puts "Here your answer, muchacho" | |
io.puts "----------------------------" | |
io.puts get_time(line) | |
elsif line =~ /quit/ | |
self.stop | |
end | |
rescue Exception => e | |
io.puts "----------------------------" | |
io.puts "There is some errors:" | |
io.puts e | |
io.puts "----------------------------" | |
self.stop | |
end | |
end | |
private | |
def get_time(line) | |
request = line.split(' ')[1] | |
cities = get_cities(request) | |
time = {} | |
time['here'] = Time.now | |
if cities.any? | |
cities.each do |city| | |
time[city] = time_in_city(city) | |
end | |
end | |
return time | |
end | |
def get_cities(string) | |
cities_array = [] | |
if string.index("?") | |
valid_string = string[string.index("?")+1, string.length-1] | |
unless valid_string.empty? | |
cities_string = valid_string.gsub('%20', ' ') | |
cities_array = cities_string.split(',') if cities_string | |
end | |
end | |
return cities_array | |
end | |
def time_in_city(city) | |
begin | |
coordinates = Geokit::Geocoders::GoogleGeocoder.geocode("#{city}") | |
time_zone_id = GoogleTimezone.fetch(coordinates.latitude, | |
coordinates.longitude).time_zone_id | |
time_zone = Timezone["#{time_zone_id}"] | |
return time_zone.utc_to_local(Time.now) if time_zone.valid? | |
rescue Exception => e | |
return 'wrong city name' | |
end | |
end | |
end | |
server = TimeServer.new | |
server.audit = true | |
server.start | |
server.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment