Class: MongoMapperExt::FileServer

Inherits:
Object
  • Object
show all
Defined in:
lib/mongomapper_ext/file_server.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ FileServer

Returns a new instance of FileServer.



6
7
8
# File 'lib/mongomapper_ext/file_server.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#_call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mongomapper_ext/file_server.rb', line 21

def _call(env)
  request = Rack::Request.new(env)
  params = request.GET

  @file = @model.find_file_from_params(params, request)
  return not_found if @file.nil?

  if @file.present?
    serving
  else
    not_found
  end
end

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/mongomapper_ext/file_server.rb', line 10

def call(env)
  if env["PATH_INFO"] =~ /^\/_files\/([^\/?]+)/
    @model = $1.classify.constantize rescue nil
    return forbidden if @model.nil?

    dup._call(env)
  else
    @app.call(env)
  end
end

#eachObject



60
61
62
63
64
65
66
# File 'lib/mongomapper_ext/file_server.rb', line 60

def each
  f = @file.get
  while part = f.read(8192)
    yield part
    break if part.empty?
  end
end

#forbiddenObject



35
36
37
38
39
40
41
# File 'lib/mongomapper_ext/file_server.rb', line 35

def forbidden
  body = "Forbidden\n"
  [403, {"Content-Type" => "text/plain",
         "Content-Length" => body.size.to_s,
         "X-Cascade" => "pass"},
   [body]]
end

#not_foundObject



52
53
54
55
56
57
58
# File 'lib/mongomapper_ext/file_server.rb', line 52

def not_found
  body = "File not found: #{@path_info}\n"
  [404, {"Content-Type" => "text/plain",
     "Content-Length" => body.size.to_s,
     "X-Cascade" => "pass"},
   [body]]
end

#servingObject



43
44
45
46
47
48
49
50
# File 'lib/mongomapper_ext/file_server.rb', line 43

def serving
  body = self
  [200, {
    "Last-Modified"  => Time.now.httpdate,
    "Content-Type"   => @file.content_type,
    "Content-Length" => @file.size.to_s
  }, body]
end