I'm trying to create a class in Ruby that checks for a type and raises an error if it finds something it didn't expect. Here's what I've got so far:
module LibHelper
class Base
def self.check_type(variables, types)
raise "Expected variables to be an array" unless variables.is_a?(Array)
raise "Expected types to be an array" unless types.is_a?(Array)
raise "Variable array and type array aren't same length" unless variables.length == types.length
variables.zip(types).each do |variable, type|
raise "Expected parameters in variables array to be symbols" unless variable.is_a?(Symbol)
raise "Expected #{eval(variable.to_s, binding)} to be type: #{type}" unless variable.is_a?(type)
end
end
def self.valid_type?(type)
valid_types = [String, Fixnum, NilClass, Hash, Symbol]
raise "Expected type to be String, Fixnum, NilClass, Hash, or Symbol got #{type}" unless valid_types.include?(type)
end
end
end
test_var = 'just_a_test_string'
LibHelper::Base.check_type([test_var], [String])
My question is what is the best way to return the name of the variable that wasn't a certain type? I'm trying to do so in this line here:
raise "Expected #{eval(variable.to_s, binding)} to be type: #{type}" unless variable.is_a?(type)
But it seems like binding might not be passed through in the scope? Ideally my return would be 'Expected test_var to be type: String'
Any thoughts or ideas?