Skip to content

Instantly share code, notes, and snippets.

@ssoroka
Created July 16, 2009 17:38
Show Gist options
  • Save ssoroka/148552 to your computer and use it in GitHub Desktop.
Save ssoroka/148552 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment