我試圖在Ruby中實現我自己的驗證。在PORO中實現驗證
這裏是一個類Item
有2次驗證,這是我需要在BaseClass
來實現:
require_relative "base_class"
class Item < BaseClass
attr_accessor :price, :name
def initialize(attributes = {})
@price = attributes[:price]
@name = attributes[:name]
end
validates_presence_of :name
validates_numericality_of :price
end
我的問題是:的驗證validates_presence_of
,並validates_numericality_of
將是類方法。我如何訪問實例對象來驗證這些類方法中的名稱和價格數據?
class BaseClass
attr_accessor :errors
def initialize
@errors = []
end
def valid?
@errors.empty?
end
class << self
def validates_presence_of(attribute)
begin
# HERE IS THE PROBLEM, self HERE IS THE CLASS NOT THE INSTANCE!
data = self.send(attribute)
if data.empty?
@errors << ["#{attribute} can't be blank"]
end
rescue
end
end
def validates_numericality_of(attribute)
begin
data = self.send(attribute)
if data.empty? || !data.integer?
@valid = false
@errors << ["#{attribute} must be number"]
end
rescue
end
end
end
end
請注意,'@@ _ validators'在這裏被'BaseClass'的所有子類共享......例如,在你的'attributes'中添加'puts'#{attribute}'。每個循環在驗證器中,然後創建一個新的'class Order
是的,我想。在ActiveModel中,'_validators'是每個單獨類的一部分(無論如何都被提取到一個模塊中)。去更新答案。 –