ismasan (owner)

Revisions

gist: 210314 Download_button fork
public
Public Clone URL: git://gist.github.com/210314.git
Embed All Files: show embed
Rack API versioner.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# USAGE ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# require 'rack/versioner'
 
# V1 = Proc.new do |env|
# body = "Hello world from V1"
# [200, {"Content-Type" => "text/html", "Content-Length" => body.size.to_s}, [body]]
# end
#
# V2 = Proc.new do |env|
# body = "Hello world from V2"
# [200, {"Content-Type" => "text/html", "Content-Length" => body.size.to_s}, [body]]
# end
#
# api = Rack::Versioner.build(:namespace => '/api', :author => 'Ismael Celis') do |m|
# m.version 'v1', V1
# m.version 'v2', V2
# m.current 'v1'
# end
#
# run api
 
module Rack
  module Versioner
    
    def self.build(options = {}, &block)
      namespace = options.fetch(:namespace, '/api')
      author = options[:author]
      
      builder = Rack::Builder.new
      versioner = Rack::Versioner::Map.new
      
      yield versioner
      
      versioner.versions.each do |num, app|
        builder.map "#{namespace}/#{num}" do
          use Headers, :version => num, :author => author
          run app
        end
      end
      
      # default
      builder.map "#{namespace}/current" do
        use Headers, :version => versioner.current_version, :author => author
        run versioner.current_app
      end
      
      builder
    end
    
    class Headers
      def initialize(app, opts = {})
        @app = app
        @version = opts[:version]
        @author = opts[:author]
      end
      
      def call(env)
        status, headers, body = @app.call(env)
        body = [] if env['REQUEST_METHOD'] == 'HEAD'
        headers["X-API-Version"] = @version.to_s if @version
        headers["X-API-Author"] = @author.to_s if @author
        [status, headers, body]
      end
      
    end
    
    
    class Map
      
      attr_reader :versions
      
      def initialize
        @versions = {}
        @current = nil
      end
      
      def version(num, app)
        @versions[num] = app
        self
      end
      
      def current(num)
        @current = num
        self
      end
      
      def current_version
        @versions[@current] ? @current : @versions.keys.last
      end
      
      def current_app
        @versions[current_version]
      end
      
    end
  end
end