Reputation: 4979
I have several ruby functions and want to check that the input is correct and also whether the input makes sense. What is a sensible way to do that?
Here's an example with one of the functions I have and what I would like to check
# Converts civil time to solar time
# civilT: Time object
# longitude: float
# timezone: fixnum
def to_solarT(civilT,longitude,timezone)
# pseudo code to check that input is correct
assert(civilT.class == Time.new(2013,1,1).class)
assert(longitude.class == 8.0.class)
assert(timezone.class == 1.class)
# More pseudocode to check if the inputs makes sense, in this case
# whether the given longitude and timezone inputs make sense or whether
# the timezone relates to say Fiji and the longitude to Scotland. Done
# using the imaginary 'longitude_in_timezone' function
assert(longitude_in_timezone(longitude,timezone))
end
I found a related question here: how to put assertions in ruby code. Is this the way to go or are there better ways to test function input in ruby?
Upvotes: 2
Views: 196
Reputation: 168101
assert
is not standard Ruby method, and is often used by test frameworks, so I don't think it is good to put it in code. Also, it does not make sense to create instances of the classes you want to check the arguments against. More straightforwardly,
def to_solarT civilT, longitude, timezone
raise "Argument error blah blah" unless Time === civilT
raise "Argument error blah blah" unless Float === longitude
raise "Argument error blah blah" unless Fixnum === timezone
...
end
Upvotes: 3
Reputation: 13886
You shouldn't do it this way. Ruby relies heavily on duck-typing. That is, if it quacks like a duck, it is a duck. i.e. Just use the objects you receive and if they do respond correctly, it's fine. If they don't, you can rescue a NoMethodError and show the appropriate output.
Upvotes: 3