Skip to content

Instantly share code, notes, and snippets.

@ivanyv
Created December 12, 2015 02:51
Show Gist options
  • Save ivanyv/ccf9a08b2423bbdef6d7 to your computer and use it in GitHub Desktop.
Save ivanyv/ccf9a08b2423bbdef6d7 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