Skip to content

Instantly share code, notes, and snippets.

@dtelaroli
Created January 5, 2015 18:43
Show Gist options
  • Save dtelaroli/4e046b341ad2a271b8f8 to your computer and use it in GitHub Desktop.
Save dtelaroli/4e046b341ad2a271b8f8 to your computer and use it in GitHub Desktop.
Rails extract routes to array
class RouteExtractor
require 'action_dispatch/routing/inspector'
attr_reader :all
def initialize
all_routes = Rails.application.routes.routes
inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes)
@all = inspector.format(ArrayFormatter.new)
end
class ArrayFormatter < ActionDispatch::Routing::ConsoleFormatter
def result
@buffer
end
def section(routes)
@buffer = routes.map do |r|
extracted = r.merge extract(r[:reqs])
OpenStruct.new(extracted)
end
end
private
def extract(reqs)
regex = /(?:(?<namespace>.*)\/)?(?<controller>.+)\#(?<action>.*)/.match(reqs)
{controller: regex[:controller], action: regex[:action], namespace: regex[:namespace]}
end
end
end
RouteExtractor.new.all #[<OpenStruct controller="invites", action="show", namespace="app", name="app_invite", verb="GET", path="/invites/:id(.:format)", reqs="app/invites#show", regexp="^\\/invites\\/([^\\/.?]+)(?:\\.([^\\/.?]+))?$">]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment