Skip to content

Instantly share code, notes, and snippets.

@benbabics
Last active September 29, 2016 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbabics/8220a902cecd2217f2b73107cc5a156a to your computer and use it in GitHub Desktop.
Save benbabics/8220a902cecd2217f2b73107cc5a156a to your computer and use it in GitHub Desktop.
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
module Api
module V1
class ProductsController < ApplicationController
# GET /products
def index
@products = Product.all
render json: @products
end
end
end
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
@benbabics
Copy link
Author

benbabics commented Sep 29, 2016

the controller path is app/controllers/api/v1/products_controller.rb

and the constraints path is app/constraints/api_constraint.rb

@benbabics
Copy link
Author

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