File: multi_route.rb

package info (click to toggle)
ruby-sinatra 4.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,932 kB
  • sloc: ruby: 17,700; sh: 25; makefile: 8
file content (89 lines) | stat: -rw-r--r-- 2,197 bytes parent folder | download | duplicates (3)
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
# frozen_string_literal: true

require 'sinatra/base'

module Sinatra
  # = Sinatra::MultiRoute
  #
  # Create multiple routes with one statement.
  #
  # == Usage
  #
  # Use this extension to create a handler for multiple routes:
  #
  #   get '/foo', '/bar' do
  #     # ...
  #   end
  #
  # Or for multiple verbs:
  #
  #   route :get, :post, '/' do
  #     # ...
  #   end
  #
  # Or for multiple verbs and multiple routes:
  #
  #   route :get, :post, ['/foo', '/bar'] do
  #     # ...
  #   end
  #
  # Or even for custom verbs:
  #
  #   route 'LIST', '/' do
  #     # ...
  #   end
  #
  # === Classic Application
  #
  # To use the extension in a classic application all you need to do is require
  # it:
  #
  #     require "sinatra"
  #     require "sinatra/multi_route"
  #
  #     # Your classic application code goes here...
  #
  # === Modular Application
  #
  # To use the extension in a modular application you need to require it, and
  # then, tell the application you will use it:
  #
  #     require "sinatra/base"
  #     require "sinatra/multi_route"
  #
  #     class MyApp < Sinatra::Base
  #       register Sinatra::MultiRoute
  #
  #       # The rest of your modular application code goes here...
  #     end
  #
  module MultiRoute
    def head(*args, &block)     super(*route_args(args), &block)  end
    def delete(*args, &block)   super(*route_args(args), &block)  end
    def get(*args, &block)      super(*route_args(args), &block)  end
    def options(*args, &block)  super(*route_args(args), &block)  end
    def patch(*args, &block)    super(*route_args(args), &block)  end
    def post(*args, &block)     super(*route_args(args), &block)  end
    def put(*args, &block)      super(*route_args(args), &block)  end

    def route(*args, &block)
      options = Hash === args.last ? args.pop : {}
      routes = [*args.pop]
      args.each do |verb|
        verb = verb.to_s.upcase if Symbol === verb
        routes.each do |route|
          super(verb, route, options, &block)
        end
      end
    end

    private

    def route_args(args)
      options = Hash === args.last ? args.pop : {}
      [args, options]
    end
  end

  register MultiRoute
end