Ruby: getting variable name

I'm trying to create a class in Ruby that checks the type and throws an error if it finds something that it wasn't expecting. Here's what I have 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, is this the best way to return the name of a variable that is not of a certain type? I am trying to do it on this line:

raise "Expected #{eval(variable.to_s, binding)} to be type: #{type}" unless variable.is_a?(type)

      

But it looks like the binding cannot be passed in scope? Ideally my return would be "The expected test_var will be of type: String"

Any thoughts or ideas?

+3


source to share


1 answer


It won't work.

There is no reliable way to get the name of the variable that the object is assigned to. Here's a contrived example:

def check_string(foo)
  bar = foo
  LibHelper::Base.check_type([bar], [String])
end

var = 123
check(var)

      

What's the correct error message in this case?

#=> Expected var to be type: String
#=> Expected foo to be type: String
#=> Expected bar to be type: String

      



Also, you can easily create objects that are not assigned to a variable:

LibHelper::Base.check_type([123], [String])

      

Better error message:

#=> Expected 123 to be type: String

      

i.e. just usevariable.inspect

+3


source







All Articles