Last active
September 29, 2016 21:42
-
-
Save benbabics/8220a902cecd2217f2b73107cc5a156a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ApiConstraint | |
attr_reader :version | |
def initialize(options) | |
@version = options.fetch(:version) | |
end | |
def matches?(request) | |
request | |
.headers | |
.fetch(:accept) | |
.include?("version=#{version}") | |
end | |
end |
This file contains hidden or 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
module Api | |
module V1 | |
class ProductsController < ApplicationController | |
# GET /products | |
def index | |
@products = Product.all | |
render json: @products | |
end | |
end | |
end |
This file contains hidden or 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
require 'api_constraint' | |
Rails.application.routes.draw do | |
namespace :api do | |
scope module: :v1, constraints: ApiConstraint.new(version: 1) do | |
resources :products | |
end | |
end | |
end |
curl -H "accept: application/json; version=1" http://localhost:3000/api/products
successfully returns: {"data":[]}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the controller path is
app/controllers/api/v1/products_controller.rb
and the constraints path is
app/constraints/api_constraint.rb