-
Notifications
You must be signed in to change notification settings - Fork 1
/
home.rb
65 lines (55 loc) · 1.62 KB
/
home.rb
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
# myapp.rb
require 'sinatra'
require 'date'
require 'open-uri'
require 'nokogiri'
require 'data_mapper'
class Event
include DataMapper::Resource
property :id, Serial
property :date, Date, :index => true
property :description, String , :length => 250
end
if ENV['VCAP_SERVICES'].nil?
DataMapper::setup(:default, "postgres://conception:Test1234@localhost/conception")
else
require 'json'
svcs = JSON.parse ENV['VCAP_SERVICES']
pgsql = svcs.detect { |k,v| k =~ /^postgresql/ }.last.first
creds = pgsql['credentials']
user, pass, host, name = %w(user password host name).map { |key| creds[key] }
DataMapper.setup(:default, "postgres://#{user}:#{pass}@#{host}/#{name}")
end
get '/' do
erb :index
end
post '/' do
begin
date = Date.parse(params[:date]) << 9
eventlist = Event.all(:date.lte => date, :date.gt => date - 14, :order => [ :date.desc ])[0,4]
unless eventlist.empty?
event = eventlist.sample
erb :result, :locals => {:date => event[:date], :description => event[:description] }
else
erb :bored, :locals => {:date => date}
end
rescue ArgumentError
halt 500, 'Illegal date'
end
end
get '/scrape' do
DataMapper.auto_migrate!
doc = Nokogiri::parse(open(File.expand_path(File.dirname(__FILE__)) + '/data/data.xml'))
cnt = 0
doc.xpath('//event').each do |event|
begin
cnt += 1
date = Date.parse(event.xpath('date').text)
description = event.xpath('description').text.strip()
Event.create(:date => date, :description => description)
puts cnt if cnt % 1000 == 0
rescue ArgumentError
end
end
"Done!"
end