Created
April 29, 2016 16:55
-
-
Save thegedge/0d5ac8ff9364f2739da0c96a913efb6e to your computer and use it in GitHub Desktop.
Rails versioned controllers via Accept header
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 V1::WelcomeController < V1::ApplicationController | |
def index | |
respond_to do |format| | |
format.welcome { render plain: "testing v1" } | |
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
class V2::WelcomeController < V1::ApplicationController | |
def index | |
respond_to do |format| | |
format.welcome { render plain: "now working with v2" } | |
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
Mime::Type.register "application/vnd.welcome.v1", :welcome, ["application/vnd.welcome.v2"] |
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 VersionConstraint | |
def initialize(version, default = false) | |
@version = version | |
@default = default | |
end | |
def matches?(request) | |
# TODO use existing MIME type parsing code | |
@default || request.headers['Accept'].include?("application/vnd.welcome.v#{@version}") | |
end | |
end | |
Rails.application.routes.draw do | |
def versioned(versions) | |
last = versions.last | |
versions.each do |version| | |
version_module = "v#{version}".to_sym | |
scope module: version_module, constraints: VersionConstraint.new(version, version == last) do | |
yield | |
end | |
end | |
end | |
versioned(1..2) do | |
get 'test', to: 'welcome#index' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment