简单的Ruby输入验证库

Fra*_*y-D 11 ruby validation input sinatra

我一直在寻找一个简单的Ruby输入验证库.一切似乎都指向ActiveRecord(或类似的).我没有使用Rails,我在没有ORM的情况下使用Sinatra.验证用户输入的最佳方法是什么(不直接与模型层绑定)?简单的事情,如"字符串长度","是数字"等.最好有一个很好的机制来声明错误消息.

Gre*_*ell 9

您可以使用Rails 3 RC中的ActiveModel :: Validations:

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
Run Code Online (Sandbox Code Playgroud)