Quantcast
Viewing latest article 11
Browse Latest Browse All 34

Rails Metal Example #5: Static Content

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:

# 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.


Viewing latest article 11
Browse Latest Browse All 34

Trending Articles