Skip to content

Instantly share code, notes, and snippets.

@arandilopez
Last active August 29, 2025 18:24
Show Gist options
  • Save arandilopez/5a094e11c31fb2f04fcbed03e1b85ad8 to your computer and use it in GitHub Desktop.
Save arandilopez/5a094e11c31fb2f04fcbed03e1b85ad8 to your computer and use it in GitHub Desktop.
Rails route helper for authentication constraints
# config/routes.rb
# Usage example
authenticated do
root to: "dashboard#index", as :dashboard
end
root to: "public#index"
# config/initializers/routing_helpers.rb
class AuthenticatedConstraint
def matches?(request)
cookies = ActionDispatch::Cookies::CookieJar.build(request, request.cookies)
if (session_id = cookies.signed[:session_id])
return true if Session.find_by(id: session_id)
end
false
rescue => _
false
end
end
module RoutingHelpers
def authenticated(options = {}, &block)
constraint = AuthenticatedConstraint.new
constraints(constraint, &block)
end
end
ActionDispatch::Routing::Mapper.include(RoutingHelpers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment