Created
June 1, 2016 20:05
-
-
Save divyanshu707/b2c6f18829d65177f6a76942eeb25551 to your computer and use it in GitHub Desktop.
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
class Latlon < ActiveRecord::Base | |
#has_one :geolocation, foreign_key: "latlon_id" | |
validates_presence_of :lat, :lon, :ts, :device_id | |
def self.track params | |
#message, status = validate_params params | |
status = Resque.enqueue(TrackWorker, params) | |
if status | |
return 200 | |
else | |
return 500 | |
end | |
end | |
def self.history params | |
params = params.with_indifferent_access | |
message, status = validate_params params | |
if status != 200 | |
return message, status | |
else | |
result = calc_history params | |
return result, 200 | |
end | |
end | |
# def geolocation | |
# self.joins(:geolocation) | |
# end | |
def self.validate_params params | |
if params[:type].nil? | |
params[:type] = "latlong" | |
end | |
if params[:device_id].nil? || params[:timestamp_start].nil? || params[:timestamp_end].nil? || !["latlong","geolocation"].include?(params[:type]) || !is_number?(params[:timestamp_start].to_s) || !is_number?(params[:timestamp_end].to_s) | |
message = {"message" => "Bad request"} | |
status = 400 | |
else | |
message = {"message" => "OK"} | |
status = 200 | |
end | |
return message, status | |
end | |
def self.is_number? string | |
true if Float(string) rescue false | |
end | |
def geolocation | |
Geolocation.find(self.geolocation_id) | |
end | |
def self.calc_history params | |
result = {"device_id" => params[:device_id], "type" => params["type"] , "points" => []} | |
if params[:type] == "latlong" | |
Latlon.where(device_id: params[:device_id]).where("ts >= #{params[:timestamp_start]} and ts <= #{params[:timestamp_end]}").order(:ts).each do |x| | |
result["points"].push([x.ts, x.lat, x.lon]) | |
end | |
else | |
Latlon.where(device_id: params[:device_id]).where("ts >= #{params[:timestamp_start]} and ts <= #{params[:timestamp_end]}").joins("inner join geolocations on geolocations.id = latlons.geolocation_id").order(:ts).each do |x| | |
result["points"].push([x.ts, x.geolocation.country, x.geolocation.city]) | |
end | |
end | |
return result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment