开发者

Validate DateTime object in Ruby

A constructor in following code receives a DateTime object in the parameter

class Test
    attr_accessor :dateTime

    # Takes DateTime object as input
    def initialize(dateTime)
        @dateTime = dateTime
    end
end

How can I validate if dateTime parameter passed to the constructor is valid DateTime object or not?

One way to find out is by using:

if dateTime.class == DateTi开发者_JAVA百科me

But is there a better way to do it?

Remember, dateTime is DateTime object and not a string


You can check it by dateTime.is_a?(DateTime) it will return boolean


Maybe use is_a? or kind_of?, to be flexible with potential subclasses.

http://www.ruby-doc.org/core/classes/Object.html#M001033


Try using the is_a? method, this way if the object is an instance of your target class (DateTime) or a subclass then you can accept it:

dateTime.is_a?(DateTime)


If all you want is to make sure that you get an instance of DateTime (or a subclass), then the other "is is_a?" answers are what you want.

However, you should consider being a little more forgiving of your inputs. What if someone hands you a string like "2011-06-28 23:31:11"? To most people, that's a DateTime even though Ruby thinks it is an instance of String. If you want to be friendlier, you could try DateTime.parse this:

begin
    dt = dt.is_a?(DateTime) ? dt : DateTime.parse(dt)
rescue ArgumentError
    # Do your failure stuff here
end

Or, if you're in Rails:

begin
    dt = dt.to_datetime
rescue ArgumentError, NoMethodError
    # Do your failure stuff here
end

These approaches give you a lot of flexibility without losing anything in the process. Be forgiving of your input but strict in your output.

For reference, in Rails 3, the following have to_datetime methods:

  • Date
  • DateTime
  • Time
  • String
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜