Created
March 15, 2016 02:44
-
-
Save gjtorikian/f999503524bb9da46dba to your computer and use it in GitHub Desktop.
Rake task to show Sinatra routes within a Rails app
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
namespace :api do | |
# Sample output is a header (listing the class name) followed by | |
# the verb + endpoint. For example: | |
# | |
# ### Within Api::Git | |
# | |
# GET /repositories/:repository_id/git | |
desc "List all the API endpoints with their verbs." | |
task :routes => :environment do | |
SKIPPABLE_FILES = [ | |
%r{app/api/staff}, | |
%r{app/api/internal}, | |
%r{app/api/serializer}, | |
%r{app/input_dependency} | |
] | |
class_endpoints = {} | |
glob = File.join(Rails.root, "app", "api", "*.rb") | |
Dir[glob].each do |file| | |
next if SKIPPABLE_FILES.any? { |s| file.match(s) } | |
require file | |
end | |
Api::App.descendants.each do |descendant| | |
class_name = descendant.to_s | |
class_endpoints[class_name] = [] | |
descendant.routes.each_pair do |verb, descendant_endpoints| | |
descendant_endpoints.each do |endpoint| | |
# Sinatra only provides routes in regexp form, so let's clean the cruft | |
route = endpoint[0].to_s.sub("(?-mix:^\\", "").sub("$)", "").gsub("\\/", "/") | |
# insert params into endpoint | |
params = endpoint[1] | |
route = route.gsub("([^\/?#]+)") { ":#{params.shift}" } | |
class_endpoints[class_name] << "#{verb} #{route}" | |
end | |
end | |
end | |
class_endpoints.sort.to_h.each_pair do |clazz, endpoints| | |
endpoints_list = endpoints.join("\n ") | |
puts <<-EOS | |
### Within #{clazz} | |
#{endpoints_list} | |
EOS | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment