Static HTML Pages on Rails App

How to create a static pages from scratch using no gems.

There is some prebuilt gem to do this, but in this particular case, I'm only looking for a lightweight solution, since I will be running this script for an application. I will need a show action to handle the rendering of the template. Since all of the following pages will be static there is no need to generate any models; there won't be any connection to the database. Only a controller is needed. One option is to command Rails to generate a controller or just do it the old school way. The first choice is :

rails generate controller static_pages ...

This last command can take options like the $ rails generate controller StaticPages home help. However for this case, I will follow the do it myself to avoid the assets, another option is to add this option ( --skip-assets ). This option is what I will use:

$ touch app/controllers/pages_controller.rb

Then in the pages_controller.rb file that gets created I will need to write the following bit of code, this adds a show action to the controller. It will render the static page. It will select the template using the parameter page. This code means that it will go to the pages folder and look for the template with a name that matches the params[: page]

class PagesController < ApplicationController
  def show
    render template: "pages/#{params[:page]}"
  end
end

Creating Route


This one is the most straightforward steps. In the routes file we add the following route:

Rails.application.routes.draw do
  get "/pages/:page" => "pages#show"
end

Now any route that is proceeded by /pages/ will work, for example, /pages/something-something. The pages should live on app/views/pages for it to work.

Creating Pages


The only need that is needed is to create the files with code that will be similar to this

$ touch app/views/pages/about.html.erb

Error handling


class PagesController < ApplicationController
    def show
      if valid_page?
        render template: "pages/#{params[:page]}"
      else
        render file: "public/404.html", status: :not_found
      end
    end

    private
    def valid_page?
      File.exist?(Pathname.new(Rails.root + "app/views/pages/#{params[:page]}.html.erb"))
    end
  end