Module: Padrino::ParamsProtection::InstanceMethods

Defined in:
padrino-core/lib/padrino-core/application/params_protection.rb

Instance Method Summary collapse

Instance Method Details

#filter_params!(params, allowed_params) ⇒ Object

Filters a hash of parameters leaving only allowed ones and possibly typecasting and processing the others.

Examples:

filter_params!( { 'a' => '1', 'b' => 'abc', 'd' => 'drop' },
                { 'a' => Integer, 'b' => true } )
# => { 'a' => 1, 'b' => 'abc' }
filter_params!( { 'id' => '', 'child' => { 'name' => 'manny' } },
                { 'id' => Integer, 'child' => { 'name' => proc{ |v| v.camelize } } } )
# => { 'id' => nil, 'child' => { 'name' => 'Manny' } }
filter_params!( { 'a' => ['1', '2', '3'] },
                { 'a' => true } )
# => { 'a' => ['1', '2', '3'] }
filter_params!( { 'persons' => { 'p-1' => { 'name' => 'manny', 'age' => '50' }, 'p-2' => { 'name' => 'richard', 'age' => '50' } } },
                { 'persons' => { 'name' => true } } )
# => { 'persons' => { 'p-1' => { 'name' => 'manny' }, 'p-2' => { 'name' => 'richard' } } }

Parameters:

  • params (Hash)

    Parameters to filter. Warning: this hash will be changed by deleting or replacing its values.

  • allowed_params (Hash)

    A hash of allowed keys and value classes or processing procs. Supported scalar classes are: Integer (empty string is cast to nil).



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'padrino-core/lib/padrino-core/application/params_protection.rb', line 90

def filter_params!(params, allowed_params)
  params.each do |key, value|
    type = allowed_params[key]
    next if value.is_a?(Array) && type
    if type.is_a?(Hash) && value.is_a?(Hash)
      if key == Inflections.pluralize(key) && value.values.first.is_a?(Hash)
        value.each do |array_index, array_value|
          value[array_index] = filter_params!(array_value, type)
        end
      else
        params[key] = filter_params!(value, type)
      end
    elsif type == Integer
      params[key] = value.empty? ? nil : value.to_i
    elsif type.is_a?(Proc)
      params[key] = type.call(value)
    elsif type != true
      params.delete(key)
    end
  end
end

#original_paramsObject

Returns the original unfiltered query parameters hash.



115
116
117
# File 'padrino-core/lib/padrino-core/application/params_protection.rb', line 115

def original_params
  @original_params || params
end