Skip to content

Instantly share code, notes, and snippets.

@seancribbs
Created March 14, 2012 20:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seancribbs/2039255 to your computer and use it in GitHub Desktop.
Save seancribbs/2039255 to your computer and use it in GitHub Desktop.
Static/file resources in Webmachine
require 'rubygems'
require 'bundler/setup'
require 'webmachine'
require 'webmachine/adapters/rack'
require 'pathname'
class StaticResource < Webmachine::Resource
def initialize
@pathname = Pathname(request.path_info[:root].to_s) + request.disp_path
end
def content_types_provided
[[Rack::Mime.mime_type(@pathname.extname, 'application/octet-stream'), :serve_file]]
end
def resource_exists?
@pathname.file?
end
def last_modified
@pathname.mtime
end
def serve_file
# Note this is probably not a good idea for big files.
# In the future, WM should be able to stream out IO objects.
@pathname.read
end
end
class HelloResource < Webmachine::Resource
def to_html
"<html><body><h1>Hello, world!</h1></body></html>"
end
end
Hello = Webmachine::Application.new do |app|
app.routes do
add [], HelloResource
add ['*'], StaticResource, :root => "static"
end
app.configure do |config|
config.adapter = :Rack
end
end
run Hello.adapter
source :rubygems
gem 'webmachine'
gem 'rack'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment