forked from davecowart/fill-murray
/
myapp.rb
75 lines (63 loc) · 2.26 KB
/
myapp.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
set :public_folder, File.dirname(__FILE__) + '/public'
set :generated_images_folder, File.dirname(__FILE__) + '/images/generated'
set :images_folder, File.dirname(__FILE__) + '/images/source'
set :static_cache_control, [:public, :max_age => 300]
gabba = Gabba::Gabba.new("UA-37788508-1", "auto")
before do
pass if request.path. == '/'
cache_control :public, :max_age => 31536000
check_sizes
end
get '/' do
send_file File.join(settings.public_folder, 'index.html')
end
get '/:width/:height' do
width = params[:width].to_i
height = params[:height].to_i
gabba.page_view("Show", "#{width}/#{height}")
return_image(width, height)
end
get '/c/:width/:height' do
width = params[:width].to_i
height = params[:height].to_i
gabba.page_view("ShowCrazy", "c/#{width}/#{height}")
return_image(width,height,:crazy)
end
get '/g/:width/:height' do
width = params[:width].to_i
height = params[:height].to_i
gabba.page_view("ShowGray", "g/#{width}/#{height}")
return_image(width,height,:grayscale)
end
private
def check_sizes
matches = /\/(\d+)\/(\d+)/.match(request.path)
width = matches[1].to_i
height = matches[2].to_i
raise error 'Bad Request' if height == nil || width == nil || height < 1 || width < 1
raise error 'Too Large' if height > 3500 || width > 3500
end
def return_image(width, height, *args)
grayscale = args.include?(:grayscale)
crazy = args.include?(:crazy)
filename = get_image_filename(width, height, grayscale, crazy)
send_file filename, type: 'image/jpeg', disposition: 'inline'
end
def get_image_filename(width, height, grayscale=false, crazy=false)
path = []
path << 'grayscale' if grayscale
path << 'crazy' if crazy
path << "#{width}x#{height}.jpg"
# send_file File.join(settings.public_folder, 'index.html')
filename = File.join(settings.generated_images_folder, *path)
return filename if FileTest.exists?(filename)
original_path = []
original_path << 'crazy' if crazy
original_path << '*.*'
original_filename = Dir.glob(File.join(settings.images_folder, *original_path)).sample
image_original = Magick::Image.read(original_filename).first
image = image_original.resize_to_fill(width,height)
image = image.quantize(256,Magick::GRAYColorspace) if grayscale
image.write(filename)
filename
end