Skip to content

Instantly share code, notes, and snippets.

@schnittchen
Created March 3, 2013 21:06
Show Gist options
  • Save schnittchen/5078299 to your computer and use it in GitHub Desktop.
Save schnittchen/5078299 to your computer and use it in GitHub Desktop.
Routing constraints tied to your app without breaking reloading in development mode
# Sometimes Constraints need to interact with controllers (fex. in order not to query the database twice), then I like
# to put them inside the controller. If you load controllers from your routes.rb (more precisely, when routes.rb is loaded),
# these won't reload in development mode.
# If your constraints live somewhere else (say, /app/constraints), it's basically all the same.
# This demonstrates an easy workaround by wrapping the fetching of constraints in a block:
class ConstraintWrapper
# Helps to load constraints from inside controllers without breaking
# development environment reloading
def initialize(&block)
@constraint_factory = block
end
def matches?(request)
@constraint_factory.call.matches?(request)
end
end
Blog::Application.routes.draw do
get '*url', to: 'my_controller#page', constraints: ConstraintWrapper.new { MyController::Constraint.new }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment