syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Rails how do I implement a wildcard route?

Recently I encountered a use-case where I wanted to write static content web content using HAML rather than HTML or markup.

If performance is an issue, probably the best way to do this is to place the HAML files under Rails.root/public/ and then use a haml2html utility to generate HTML files in the same directory.

The problem with this idea is that it saddles the webmaster with an administrative task. On the other hand if the site is usually under heavy load, the webmaster is probably already carrying many tasks and the running of haml2html via a scheduler should not be a big deal.

If the site serves light traffic loads, another way to do it is to place the HAML files in a directory under Rails.root/apps/views/ and then use a wildcard route to help Rails serve the HAML files as HTML.

So, in Rails how do I implement a wildcard route?

First I need to create a controller unless I already have one.

This shell command demonstrates the syntax to create a Rails controller:
bin/rails generate controller posts
Then, I place syntax at the end of Rails.root/config/routes.rb which looks like this:
get ':controller(/:action)'
Next, I mkdir a directory like this:
mkdir app/views/posts/
And, I place my static HAML code there. For example:
echo '%h1 Hello World' > app/views/posts/post1.haml
Then, I use a browser to send a GET request to the server:
localhost:3000/posts/post1
And, I should see this HTML somewhere in the response:
<h1>Hello World</h1>
So, implementing a wild-card route in Rails is both easy and useful for serving static content from under Rails.root/app/views.
syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me