Serving static pages with Rails Metal is actually very simple. Here are the assumptions we’re making.
- Each static page’s content is made up of valid HTML.
- Each static page has a path and content stored in a StaticPage object as defined by the StaticPage model.
- If the path browsed matches the path in a StaticPage object, the content is what is to be delivered.
Here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 | # Allow the metal piece to run in isolation require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails) class StaticPages def self.call(env) if sp = StaticPage.find_by_path(env["PATH_INFO"]) [200, {"Content-Type" => "text/html"}, [sp.content]] else [404, {"Content-Type" => "text/html"}, ["Not Found"]] end end end |
As you can see all there is to this one is finding the StaticPage object with the right path and returning a success response with the object’s content as the body.
Feel free to check out the other 9 Ways to Use Rails Metal.





2 Comments »
jDeppen
July 8, 2009
I’m not too familiar with Metal. Doesn’t page caching do the same thing? I thought it avoided the Rails stack.
Chuck
July 8, 2009
Metal does avoid the Rails stack. The main difference between this example and page caching is that this example pulls the page content from the database and renders it in the Rack response. Page caching stores the page content when it is requested and then returns the content from the cache for subsequent requests.
Leave a comment