File: required_params.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 (73 lines) | stat: -rw-r--r-- 1,683 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
# frozen_string_literal: true

require 'sinatra/base'

module Sinatra
  # = Sinatra::RequiredParams
  #
  # Ensure required query parameters
  #
  # == Usage
  #
  # Set required query parameter keys in the argument.
  # It'll halt with 400 if required keys don't exist.
  #
  #   get '/simple_keys' do
  #     required_params :p1, :p2
  #   end
  #
  # Complicated pattern is also fine.
  #
  #   get '/complicated_keys' do
  #     required_params :p1, :p2 => [:p3, :p4]
  #   end
  #
  # === Classic Application
  #
  # In a classic application simply require the helpers, and start using them:
  #
  #     require "sinatra"
  #     require "sinatra/required_params"
  #
  #     # The rest of your classic application code goes here...
  #
  # === Modular Application
  #
  # In a modular application you need to require the helpers, and then tell
  # the application to use them:
  #
  #     require "sinatra/base"
  #     require "sinatra/required_params"
  #
  #     class MyApp < Sinatra::Base
  #       helpers Sinatra::RequiredParams
  #
  #       # The rest of your modular application code goes here...
  #     end
  #
  module RequiredParams
    def required_params(*keys)
      _required_params(params, *keys)
    end

    private

    def _required_params(p, *keys)
      keys.each do |key|
        if key.is_a?(Hash)
          _required_params(p, *key.keys)
          key.each do |k, v|
            _required_params(p[k.to_s], v)
          end
        elsif key.is_a?(Array)
          _required_params(p, *key)
        else
          halt 400 unless p.respond_to?(:key?) && p&.key?(key.to_s)
        end
      end
      true
    end
  end

  helpers RequiredParams
end