Skip to content

Instantly share code, notes, and snippets.

@chrmod
Created May 17, 2013 13:32
Show Gist options
  • Save chrmod/5599051 to your computer and use it in GitHub Desktop.
Save chrmod/5599051 to your computer and use it in GitHub Desktop.
A rack middleware that redirect URLs that have ID to URLs that have SLUG. Should run well with typical friendly_id setup.
class RedirectOldUrl
RESOURCES_WITH_SLUGS = [
"conferences",
"users",
"events",
"articles",
"partners"
]
def initialize(app)
@app = app
end
def call(env)
@request = Rack::Request.new(env)
if env["HTTP_ACCEPT"].include?("text/html") && is_old_url?
[301, {"Location" => "http://#{host}#{new_path}"}, []]
else
@app.call(env)
end
end
def host
(@request.port == 80) ? @request.host : @request.host_with_port
end
def new_path
id = @route_params[:id]
model = @route_params[:controller].classify.constantize
slug = model.find(id).slug || id
@route_params[:id] = slug
@route_params[:only_path] = true
Rails.application.routes.url_for(@route_params)
end
def is_old_url?
@route_params = Rails.application.routes.recognize_path(@request.path)
# Check if ID is an integer and controller is on list
!!(@route_params[:id] =~ /^[-+]?[0-9]+$/) && RESOURCES_WITH_SLUGS.include?(@route_params[:controller])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment