forked from rickychilcott/factors.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factors_app.rb
92 lines (75 loc) · 2.24 KB
/
factors_app.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
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
require 'rubygems'
require 'bundler/setup'
Bundler.require
Mongoid.load!("config/mongoid.yml")
I18n.config.enforce_available_locales=false
require "sinatra/namespace"
require './number'
require './lib/workers/factor_and_divisor_worker'
require './lib/pari_gp'
require './lib/delimited'
class FactorsApp < Sinatra::Base
register Sinatra::Namespace
get '/application.js' do
coffee :'application'
end
# Homepage
get '/' do
haml :index
end
get '/about' do
haml :about
end
# Get a random number
get '/random' do
random_number = rand(0..1_000_000_000_000_000_000_000)
redirect to("/numbers/#{random_number}")
end
get '/random-prime' do
random_value = Number.where(prime: true).pluck(:value).sample
redirect to("/numbers/#{random_value}")
end
# Show a number
get '/numbers/:number' do
val = Number.ensure_integer_as_string(params[:number])
number = Number.find_or_initialize_by(value: val)
haml :'numbers/get', locals: { number: number}
end
# Submit a number
post '/numbers/:number' do
val = Number.ensure_integer_as_string(params[:number])
number = Number.find_or_initialize_by(value: val)
if number.incomplete?
number.status = 'queued'
number.save
FactorAndDivisorWorker.perform_async(number.value)
end
redirect to("/numbers/#{val}")
end
namespace '/api' do
get "/numbers/recent" do
Number.order_by(created_at: :desc).limit(10).pluck(:value).to_json
end
get '/numbers/:number' do
val = Number.ensure_integer_as_string(params[:number])
number = Number.find_or_initialize_by(value: val)
{ value: number.value,
status: number.status,
factors: number.factors,
divisors: number.divisors,
prime: number.prime,
factorization_duration: number.factorization_duration
}.to_json
end
get '/random_number' do
random_number = rand(0..1_000_000_000_000_000_000_000)
redirect to("/api/numbers/#{random_number}")
end
get '/random-prime' do
random_value = Number.where(prime: true).pluck(:value).sample
redirect redirect to("/api/numbers/#{random_value}")
end
end
# start the server if ruby file executed directly
run! if app_file == $0
end