Created
January 5, 2015 18:43
-
-
Save dtelaroli/4e046b341ad2a271b8f8 to your computer and use it in GitHub Desktop.
Rails extract routes to array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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