对于非ActiveRecord对象的Validation,我们不能简单的include ActiveRecord::Validations
我们需要写一个module,如ValidatingNonARObjects/lib/validateable.rb
[code]
module Validateable
[:save, :save!, :update_attribute].each{|attr| define_method(attr){}}
def method_missing(symbol, *params)
if(symbol.to_s =~ /(.*)_before_type_cast$/)
send($1)
end
end
def self.append_features(base)
super
base.send(:include, ActiveRecord::Validations)
end
end
[/code]
这样我们就可以对非ActiveRecord对象中使用validations了,如:
[code]
class Person
include Validateable
attr_accessor :age
validates_numericality_of :age
end
[/code]
我们需要写一个module,如ValidatingNonARObjects/lib/validateable.rb
[code]
module Validateable
[:save, :save!, :update_attribute].each{|attr| define_method(attr){}}
def method_missing(symbol, *params)
if(symbol.to_s =~ /(.*)_before_type_cast$/)
send($1)
end
end
def self.append_features(base)
super
base.send(:include, ActiveRecord::Validations)
end
end
[/code]
这样我们就可以对非ActiveRecord对象中使用validations了,如:
[code]
class Person
include Validateable
attr_accessor :age
validates_numericality_of :age
end
[/code]
本文介绍了一种在非ActiveRecord对象上实现验证的方法。通过创建一个名为Validateable的模块,并将其包含在非ActiveRecord类中,可以为这些类提供类似于ActiveRecord的验证功能。

被折叠的 条评论
为什么被折叠?



