ssoroka (owner)

Revisions

gist: 148552 Download_button fork
public
Public Clone URL: git://gist.github.com/148552.git
Embed All Files: show embed
validate_request_parameters.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
# renders public/400.html on requests that do not supply expected parameters.
module ValidateRequestParameters
  # accept_only :string, :for => [:first_name, :last_name]
  # accept_only :number, :for => :age
  # accept_only :hash, :for => :categories
  # accept_only :boolean, :for => :wants_newsletter
  # accept_only String::VALID_POSTAL, :for => :postal_code
  # accept_only /\d{3}\-\d{4}/, :for => :phone
  module ClassMethods
    def accept_only(param_type, options)
      fields = Array(options[:for])
      before_filter do |controller|
        fields.each{|field|
          val = controller.params[field]
          acceptable = val.nil? # blank values are always acceptable
          acceptable ||= case param_type
          when Regexp
            val.kind_of?(String) && val =~ param_type
          when :string
            val.kind_of?(String)
          when :array
            val.kind_of?(Array)
          when :digits, :number, :integer, :fixnum
            val.kind_of?(String) && val =~ /^\d+$/
          when :decimal
            val.kind_of?(String) && val =~ /^\d+(\.\d+)?$/
          when :signed_digits, :signed_number, :signed_integer, :signed_fixnum
            val.kind_of?(String) && val =~ /^[\+\-]?\d+$/
          when :signed_decimal
            val.kind_of?(String) && val =~ /^[\+\-]?\d+(\.\d+)?$/
          when :hash
            val.kind_of?(Hash)
          when :boolean
            val.kind_of?(String) && val =~ /^(0|1)$/
          when :date
            val.kind_of?(Date)
          when :datetime
            val.kind_of?(DateTime)
          else
            raise Exception.new("There is no ValidateRequestParameters param type called #{param_type}. Check class docs.")
          end
          controller.send :render_optional_error_file, 400 unless acceptable
        }
      end
    end
  end
  
  def self.included(base)
    base.extend ClassMethods
  end
end