Skip to content

Instantly share code, notes, and snippets.

@ghiculescu
Last active October 28, 2016 12:56
Show Gist options
  • Save ghiculescu/e6ddeb466ec42e8e074a4d67ac2dbc00 to your computer and use it in GitHub Desktop.
Save ghiculescu/e6ddeb466ec42e8e074a4d67ac2dbc00 to your computer and use it in GitHub Desktop.
# i wish i did this in JS
require 'sinatra'
require 'fileutils'
require 'json'
require 'date'
require 'time'
require 'byebug'
get "/devices" do
content_type :json
Dir.glob("files/*").to_json
end
get "/:device_id/:date" do
content_type :json
files = if params[:device_id] == 'all'
Dir.glob("files/*").map {|f|
data = File.read(f).each_line.to_a.map(&:strip).find_all {|t|
start = Date.parse(params[:date]).to_time
finish = start + 86400
t = Time.at(t.to_i)
t >= start && t <= finish
}
[f, data]
}.to_h
else
File.read("files/#{params[:device_id]}").each_line.to_a.map(&:strip).find_all {|t|
start = Date.parse(params[:date]).to_time
finish = start + 86400
t = Time.at(t.to_i)
t >= start && t <= finish
}
end.to_json
end
get "/:device_id/:from/:to" do
content_type :json
files = if params[:device_id] == 'all'
Dir.glob("files/*").map {|f|
data = File.read(f).each_line.to_a.map.find_all {|t|
start = Date.parse(params[:from]).to_time rescue Time.at(params[:from].to_i)
finish = Date.parse(params[:to]).to_time rescue Time.at(params[:to].to_i)
t = Time.at(t.to_i)
t >= start && t < finish
}
[f, data]
}.to_h
elsif File.exist?(File.read("files/#{params[:device_id]}"))
File.read("files/#{params[:device_id]}").each_line.to_a.map(&:strip).find_all {|t|
start = Date.parse(params[:from]).to_time rescue Time.at(params[:from].to_i)
finish = Date.parse(params[:to]).to_time rescue Time.at(params[:to].to_i)
t = Time.at(t.to_i)
t >= start && t < finish
}
else
[]
end.to_json
end
post "/:device_id/:timestamp" do
FileUtils.mkdir_p("files")
File.open("files/#{params[:device_id]}", 'a') { |f| f.puts params[:timestamp]}
status 200
end
post "/clear_data" do
FileUtils.rm_rf("files")
status 200
end
@byronmejia
Copy link

Wow. So much better than JavaScript!

@CallumJHays
Copy link

That was fun! We should do live code challenges more often.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment