Skip to content

Instantly share code, notes, and snippets.

@jvoorhis
Created February 11, 2013 23:46
Show Gist options
  • Save jvoorhis/4758716 to your computer and use it in GitHub Desktop.
Save jvoorhis/4758716 to your computer and use it in GitHub Desktop.
Static asset resource for webmachine.rb
app.routes do
add ['*'], Resources::Static
end
module Resources
# Renders files on disk
class Static < Webmachine::Resource
def content_types_provided
# TODO replace this list with something sane / complete, package as a
# standalone library.
[
['application/ecmascript', :to_bytes],
['application/javascript', :to_bytes],
['application/xml', :to_bytes],
['image/png', :to_bytes],
['text/css', :to_bytes],
['text/ecmascript', :to_bytes],
['text/html', :to_bytes],
['text/javascript', :to_bytes],
['text/xml', :to_bytes],
]
end
def resource_exists?
File.file? map_path(request.uri.path)
end
def to_bytes
# FIXME stream results
IO.read map_path(request.uri.path)
end
private
def map_path(path)
path = path.sub %r{^/}, ''
path = File.expand_path(path, static_root)
path if path.start_with?(static_root)
end
def static_root
File.expand_path('../../public', File.dirname(__FILE__))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment