Skip to content

Instantly share code, notes, and snippets.

@kaspth
Last active April 6, 2023 16:57
Show Gist options
  • Save kaspth/4e1968c30aa77791926696d0fbe9d22c to your computer and use it in GitHub Desktop.
Save kaspth/4e1968c30aa77791926696d0fbe9d22c to your computer and use it in GitHub Desktop.
`draw` method to explore routes in the console
# All these requires are just for running via `irb`, if using `bin/rails console` you probably just need the method.
require "active_support/all" # Got an inflector NoMethodError, so I'm just being lazy here.
require "action_dispatch"
require "action_dispatch/routing/route_set"
require "action_dispatch/routing/inspector"
require "action_controller" # For the ActionController::Parameters autoload, which any route helper uses.
# Console helper play around with the routing DSL and tweak an individual route you're building.
#
# draw { resources :posts } => routes
# routes.url_helpers.photos_url(host: "example.com") # => example.com/photos
#
# Basically what `bin/rails routes` does:
# https://github.com/rails/rails/blob/58e7fc18cbe3fce68ce86566b808ce98c3009477/railties/lib/rails/commands/routes/routes_command.rb#L25
def draw(&block)
ActionDispatch::Routing::RouteSet.new.tap do |route_set|
route_set.draw(&block)
formatter = ActionDispatch::Routing::ConsoleFormatter::Sheet.new
pp ActionDispatch::Routing::RoutesInspector.new(route_set.routes).format(formatter)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment