mirror of
https://github.com/sinatra/sinatra
synced 2023-03-27 23:18:01 -04:00
serving static files
This commit is contained in:
parent
95ab3666e5
commit
036c3aa42e
2 changed files with 38 additions and 0 deletions
|
@ -16,4 +16,8 @@ module Kernel
|
|||
Sinatra::EventContext.class_eval &block
|
||||
end
|
||||
|
||||
def static(path, root)
|
||||
Sinatra::StaticEvent.new(path, File.join(File.dirname($0) + root))
|
||||
end
|
||||
|
||||
end
|
||||
|
|
|
@ -144,4 +144,38 @@ module Sinatra
|
|||
|
||||
end
|
||||
|
||||
class StaticEvent < Event
|
||||
|
||||
def initialize(path, root, register = true)
|
||||
super(:get, path, register)
|
||||
@root = File.expand_path(root)
|
||||
end
|
||||
|
||||
def recognize(path)
|
||||
canserve = File.dirname(path) == @path
|
||||
@filename = File.join(@root, path.gsub(/^#{@path}/, ''))
|
||||
canserve && File.exists?(@filename)
|
||||
end
|
||||
|
||||
def attend(request)
|
||||
puts 'attend ' + self.inspect
|
||||
@body = self
|
||||
end
|
||||
|
||||
def status; 200; end
|
||||
|
||||
def headers; {}; end
|
||||
|
||||
def body; @body; end
|
||||
|
||||
def each
|
||||
File.open(@filename, "rb") { |file|
|
||||
while part = file.read(8192)
|
||||
yield part
|
||||
end
|
||||
}
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue