Module: Sinatra::FilteringParameters

Defined in:
lib/sinatra/filtering_parameters.rb,
lib/sinatra/filtering_parameters/version.rb

Constant Summary collapse

VERSION =

sinatra-filtering_parameters version

"0.1.1"

Class Method Summary collapse

Class Method Details

.allow(params, filters) ⇒ Object



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
# File 'lib/sinatra/filtering_parameters.rb', line 20

def allow(params, filters)
  allow_params = {}
  _filters = [filters].flatten
  [filters].flatten.each do |filter|
    _filters.shift
    case filter
    when Symbol, String
      filter = filter.to_s
      next unless params.is_a?(Hash)

      if params.has_key?(filter)
        if params[filter].is_a?(Hash)
          allow_param = allow(params[filter], _filters)
          allow_params[filter] = allow_param unless allow_param.empty?
        else
          allow_params[filter] = params[filter]
        end
      end
    when Hash
      _params = {}
      filter.keys.map(&:to_s).each { |k| _params[k] = params[k] if params.has_key?(k) }
      _params.each do |key, value|
        case value
        when Array
          [value].flatten.each do |v|
            allow_param = allow(v, filter.values)
            unless allow_param.empty?
              allow_params[key] ||= []
              allow_params[key] << allow_param
            end
          end
        else
          if value.keys.all? { |k| k =~ /\A-?\d+\z/ }
            value.each do |k, v|
              allow_param = allow(v, filter.values)
              unless allow_param.empty?
                allow_params[key] ||= {}
                allow_params[key][k] = allow_param
              end
            end
          else
            allow_param = allow(value, filter.values)
            allow_params[key] = allow_param unless allow_param.empty?
          end
        end
      end
    end
  end
  allow_params
end

.registered(app) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/sinatra/filtering_parameters.rb', line 6

def registered(app)
  app.set(:allow) do |*filters|
    condition do
      original = @params.dup
      @params.clear
      %w[ splat captures ].each do |name|
        @params[name] = original.delete(name) if original.include?(name)
      end
      allow_params = Sinatra::FilteringParameters.allow(original, filters)
      @params.merge! indifferent_params(allow_params)
    end
  end
end