Last active
April 7, 2016 12:05
-
-
Save cookiefission/2d295b9e8a473e8e5ec1350a06a7e58d to your computer and use it in GitHub Desktop.
Hack for url versioned routes in Rails.
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
Rails.application.routes.draw do | |
versioned do | |
resources :flights | |
end | |
# Using the `versioned` helper with v1/ v2/ and v3/ directories existing | |
# is equivalent to doing: | |
# namespace :v1 do | |
# resources :flights | |
# end | |
# namespace :v2 do | |
# resources :flights | |
# end | |
# namespace :v3 do | |
# resources :flights | |
# 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
# Load this somewhere in initialisation. | |
module ActionDispatch::Routing | |
class Mapper | |
def versioned(&block) | |
self.instance_eval(&Versioned.new.version(&block)) | |
end | |
class Versioned | |
def initialize | |
@routes = Hash.new { |h, k| h[k] = Set.new } | |
end | |
def version(&block) | |
self.instance_eval(&block) | |
routes_proc | |
end | |
def method_missing(method, *args) | |
controller_versions.each do |version| | |
@routes[version] << [method, *args] | |
end | |
end | |
def controller_versions | |
versions = Set.new | |
Dir[Rails.root.join("app/controllers/api/*")].each do |dir| | |
versions << File.basename(dir)[1] | |
end | |
versions | |
end | |
def routes_proc | |
routes = @routes | |
Proc.new do | |
routes.each do |version, version_routes| | |
namespace :"v#{version}" do | |
version_routes.each { |route| send(*route) } | |
end | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment