Skip to content

Instantly share code, notes, and snippets.

@kenkeiter
Last active December 17, 2015 06:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenkeiter/5563820 to your computer and use it in GitHub Desktop.
Save kenkeiter/5563820 to your computer and use it in GitHub Desktop.
If you've tried to mount RESTful resources at '/' with Padrino, you've probably run into issues with its router, and had to :map each action (or develop some idiom to generate the mappings for you). Padrino's router is pretty opinionated; when you're using named controllers, you'll want to make use of `:parent` directives -- which you can't, if …
# You'll need to add 'rack-rewrite' to your Gemfile.
require 'rack/rewrite'
require File.expand_path("../config/boot.rb", __FILE__)
# lazy load the application, instantiating routes.
application = Padrino.application
# Determine which routes NOT to redirect to your root resource.
reserved_routes = YourProject::App.routes.map{|r|
r.path_for_generation.scan /[a-zA-Z0-9]+/i
}.flatten!.uniq!
# Add any directories or files under #{Padrino.root}/public.
reserved_routes.concat Dir.entries(Padrino.root('public')).select{ |f|
not f.start_with?('.')
}
# Use Rack::Rewrite to check if the request URL begins with a
# reserved_route name. If it does not, rewrite the URL
# internally so that it directs to your desired "root" resource
# controller. Similarly, setup a 302 redirect for any requests
# made from the outside which should be directed to the root
# resource controller, as well.
use Rack::Rewrite do
rewrite %r{^\/(?!#{reserved_routes.join('|')})(.*)}, '/users/$1'
r302 %r{^/users/(.*)$}, '/$1'
end
# Start the app.
run application
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment