Skip to content

Instantly share code, notes, and snippets.

@tachyons
Forked from ivanyv/application.amp.erb
Created April 13, 2016 09:51
Show Gist options
  • Save tachyons/2226263cbb664164d2a5e926b349f695 to your computer and use it in GitHub Desktop.
Save tachyons/2226263cbb664164d2a5e926b349f695 to your computer and use it in GitHub Desktop.
Easy Google AMP on Rails
<html>
<head>
<link rel="canonical" href="<%= current_uri_sans_amp %>">
</head>
...
</html>
<html>
<head>
<link rel="amphtml" href="/amp<%= current_uri %>">
<link rel="canonical" href="<%= current_uri %>">
</head>
...
</html>
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :force_amp, if: -> { request.path_parameters[:amp] }
private
def force_amp
request.format = 'amp'
end
end
# config/initializers/mime_types.rb
Mime::Type.register 'text/html', :amp
# config/routes.rb
Rails.application.routes.draw do
scope '(:amp)', constraints: { amp: /amp/ } do
# Put here all routes that also have AMP variants
root to: 'home#index'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment