Repository navigation
Expand file tree
/
Copy pathapp.rb
More file actions
97 lines (88 loc) · 2.29 KB
/
Copy pathapp.rb
File metadata and controls
97 lines (88 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
require 'sinatra'
require 'sinatra/activerecord'
require 'json'
configure do
ROOT = ::File.dirname(__FILE__)
Dir.glob(ROOT + '/models/*', &method(:require))
require 'erb'
@db_settings = YAML::load(ERB.new(IO.read("config/database.yml")).result)
ActiveRecord::Base.establish_connection @db_settings['development']
end
configure :development do |config|
config.enable :reload
end
get '/fix' do
redirect '/foxes'
end
post '/fix' do
Device.find_or_create_by_device_id_and_sim_id :device_id => params[:device_id], :sim_id => params[:sim_id]
fix = Fix.create :lat => params[:lat],
:lon => params[:lon],
:alt => params[:alt],
:acc => params[:acc],
:client_time => params[:client_time] || Time.now,
:provider_id => params[:provider_id],
:device_id => params[:device_id],
:user_id => params[:user_id],
:speed => params[:speed],
:bearing => params[:bearing]
content_type :json
if fix.save
Fox.all.to_json
else
puts "Error: #{fix.errors.first.full_messages}"
error 400, fix.errors.to_json
end
end
get '/foxes' do
content_type :json
Fox.all.to_json
end
post '/fox' do
fox_attrs = params.reject { |k, v| ![:name, :lat, :lon].include?(k) }
if params[:id]
fox = Fox.find_by_id params[:id]
error 400, "Fox not found" and return if fox.nil?
fox.update_attributes fox_attrs
else
Fox.create fox_attrs
end
content_type :json
Fox.all.to_json
end
delete '/fox/:id' do |fox_id|
content_type :json
fox = Fox.find_by_id fox_id
if fox
fox.destroy
Fox.all.to_json
else
error 400, "Fox [#{fox_id}] isn't found" and return if fox.nil?
end
end
post '/foxes/:id' do |fox_id|
content_type :json
fox = Fox.find fox_id
if fox.present?
fox.update_attributes :name => params[:name], :lat => params[:lat], :lon => params[:lon]
redirect '/foxes'
else
error 400, "Fox [#{fox_id}] not found"
end
end
get '/users' do
content_type :json
User.all.to_json
end
get '/users/:id/devices' do |user_id|
content_type :json
u = User.find_by_id user_id
if u.present?
u.devices.to_json
else
error 400, "User [#{user_id}] not found"
end
end
get '/devices' do
Device.all.to_json
end