I've been looking all over the place for a simple input validation library for Ruby. Everything seems to point towards ActiveRecord (or similar). I'm not using Rails, I'm using Sinatra without an ORM. What's the best approach for validating user input (without tying directly to the model layer)? Simple things like "string length", "is numeric" etc. Preferably with a nice mechanism for declaring error messages.
+1
A:
You could use ActiveModel::Validations, from Rails 3 RC:
require 'active_model'
# this appears to be a bug in ActiveModel - it uses this, but does not require it
require 'active_support/core_ext/hash'
class Model
include ActiveModel::Validations
attr_accessor :name
validates_presence_of :name
end
m = model.new
puts m.valid? # false
m.name = "John Doe"
puts m.valid? # true
Greg Campbell
2010-08-05 18:51:45
Thanks for the suggestion and example. However, I'm looking for something that does not tie validations to models.
Franky-D
2010-08-06 11:45:07
The example I gave will work with any Ruby class that has attributes - can you give an example (code or pseudocode) of the way you'd like validation to work?
Greg Campbell
2010-08-06 18:03:31
I ended up going this route. Thanks.
Franky-D
2010-08-29 19:32:15