在Ruby中验证DateTime对象
下面代码中的构造函数在参数中接收DateTime对象在Ruby中验证DateTime对象,ruby,datetime,object,validation,Ruby,Datetime,Object,Validation,下面代码中的构造函数在参数中接收DateTime对象 class Test attr_accessor :dateTime # Takes DateTime object as input def initialize(dateTime) @dateTime = dateTime end end 如何验证传递给构造函数的dateTime参数是否为有效的dateTime对象 找到答案的一种方法是使用: if dateTime.class == D
class Test
attr_accessor :dateTime
# Takes DateTime object as input
def initialize(dateTime)
@dateTime = dateTime
end
end
如何验证传递给构造函数的dateTime参数是否为有效的dateTime对象
找到答案的一种方法是使用:
if dateTime.class == DateTime
但是有没有更好的方法呢
请记住,dateTime是dateTime对象,而不是字符串。您可以通过dateTime检查它。is_a?(dateTime)它将返回布尔值可能使用
is_a?
或类来灵活处理潜在的子类
尝试使用is_?
方法,这样,如果对象是目标类(DateTime)或子类的实例,则可以接受它:
dateTime.is_a?(DateTime)
如果您只想确保获得DateTime实例(或子类),那么另一个“isis_a?
”答案就是您想要的
但是,你应该考虑对你的投入多一点宽容。如果有人递给你一根像“2011-06-28 23:31:11”这样的线怎么办?对大多数人来说,这是一个日期时间,尽管Ruby认为它是String的一个实例。如果您想变得更友好,可以尝试以下方法:
或者,如果您在Rails中:
begin
dt = dt.to_datetime
rescue ArgumentError, NoMethodError
# Do your failure stuff here
end
这些方法为您提供了很大的灵活性,而且不会在过程中损失任何东西。原谅你的输入,但严格要求你的输出
作为参考,在Rails 3中,以下方法有to_datetime
方法:
我所说的“valid”,是指DateTime的实例(或它的子类)Rails的第二个建议,对于空字符串似乎不起作用:dt=dt.to_DateTime#=nil
@Chris:dt=dt.presence
并添加一个显式的nil
检查。或者dt.presence.to_datetime
并将其作为命名错误捕获。
begin
dt = dt.to_datetime
rescue ArgumentError, NoMethodError
# Do your failure stuff here
end