Permalink
Browse files

serving static files

  • Loading branch information...
1 parent 95ab366 commit 036c3aa42e449001bedd1e42053574ae82ba386f blake.mizerany@gmail.com committed Sep 17, 2007
Showing with 38 additions and 0 deletions.
  1. +4 −0 lib/sinatra/dsl.rb
  2. +34 −0 lib/sinatra/event.rb
View
4 lib/sinatra/dsl.rb
@@ -16,4 +16,8 @@ def helpers(&block)
Sinatra::EventContext.class_eval &block
end
+ def static(path, root)
+ Sinatra::StaticEvent.new(path, File.join(File.dirname($0) + root))
+ end
+
end
View
34 lib/sinatra/event.rb
@@ -144,4 +144,38 @@ def run_through_after_filters(context)
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

0 comments on commit 036c3aa

Please sign in to comment.