Class: Attacheable::PhotoHandler

Inherits:
Mongrel::HttpHandler
  • Object
show all
Defined in:
lib/attacheable/photo_handler.rb

Instance Method Summary collapse

Constructor Details

#initialize(prefix, options) ⇒ PhotoHandler

Returns a new instance of PhotoHandler.



3
4
5
6
# File 'lib/attacheable/photo_handler.rb', line 3

def initialize(prefix, options)
  @prefix = prefix
  @class_name = options[:class_name]
end

Instance Method Details

#klassObject



12
13
14
# File 'lib/attacheable/photo_handler.rb', line 12

def klass
  @class_name.constantize
end

#loggerObject



8
9
10
# File 'lib/attacheable/photo_handler.rb', line 8

def logger
  ActiveRecord::Base.logger
end

#process(request, response) ⇒ Object



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
# File 'lib/attacheable/photo_handler.rb', line 16

def process(request, response)
  if File.exists?(Attacheable.root+"/public#{@prefix}/#{request.params["PATH_INFO"]}")
    response.start(200) do |headers, out|
      headers["Content-Type"] = "image/jpeg"
      out.write(File.read(Attacheable.root+"/public#{@prefix}/#{request.params["PATH_INFO"]}"))
    end
    return
  end

  start_time = Time.now
  photo, data = klass.data_by_path_info(request.params["PATH_INFO"].split("/"))
  if photo
    response.start(200) do |headers, out|
      headers["Content-Type"] = photo.content_type
      out.write(data)
    end
  else
    response.start(404) do |headers, out|
      headers["Content-Type"] = "text/plain"
      out.write("No such image\n")
    end
  end
  logger.info "Processed request in #{Time.now - start_time} seconds\n  URI: #{request.params["REQUEST_URI"]}\n\n"
rescue Exception => e
  logger.info "!! Internal server error\nURI: #{request.params["REQUEST_URI"]}\n#{e}\n#{e.backtrace.join("\n")}"
  logger.flush
  response.start(200) do |headers, out|
    headers["Content-Type"] = "text/plain"
    out.write("Some error on server\n")
  end
end