Generating and Serving the Manifest in Rails
Now that we understand the purpose of a Web App Manifest, we need to create and serve this file dynamically in our Rails application.
1. Creating the manifest.json
File
We will store the manifest file in the app/views/layouts
directory and serve it dynamically using Rails' render
method.
Create a new file at app/views/layouts/manifest.json.jbuilder
and define its structure:
json.name "Rails PWA"
json.short_name "PWA"
json.start_url root_url
json.display "standalone"
json.background_color "#ffffff"
json.theme_color "#ff5722"
json.icons [
{
src: image_url("icons/icon-192x192.png"),
sizes: "192x192",
type: "image/png"
},
{
src: image_url("icons/icon-512x512.png"),
sizes: "512x512",
type: "image/png"
}
]
2. Creating a Route for the Manifest
Next, we need to define a route in config/routes.rb
to serve the manifest file:
get "/manifest.json", to: "manifests#show", defaults: { format: :json }
3. Creating the Controller to Serve the Manifest
Generate a new controller named ManifestsController
:
rails generate controller Manifests
Modify app/controllers/manifests_controller.rb
to render the JSON manifest:
class ManifestsController < ApplicationController
def show
respond_to do |format|
format.json { render template: "layouts/manifest.json.jbuilder" }
end
end
end
4. Linking the Manifest in the Application Layout
Finally, include the manifest file in the <head>
section of app/views/layouts/application.html.erb
:
<link rel="manifest" href="<%= url_for('/manifest.json') %>">
At this point, our Rails app serves a dynamically generated Web App Manifest.
The next step is to customize app icons and splash screens for different devices.