I'm writing some tests to verify the behaviour of some regular expressions to be used within a Ruby console application. I'm trying to define constant class level fields on a class not meant to be instantiated (just supposed to have constant RE values defined on it. I'm having trouble defining this properly using Ruby idiom (I have C++/C# background).
First I tried to define a class constant
class Expressions
# error is on following line (undefined method DATE)
Expressions.DATE = /(?<Year>\d{4})-(?<Month>\d{2})-(?<Day>\d{2})/
end
class MyTest < Test::Unit::TestCase
def setup
@expression = Expressions::DATE
end
def test
assert "1970-01-01" =~ @expression
end
end
this just produces error: undefined method `DATE=' for Expressions:Class (NoMethodError)
Next I tried class attributes:
class Expressions
@@Expressions.DATE = /(?<Year>\d{4})-(?<Month>\d{2})-(?<Day>\d{2})/
end
class MyTest < Test::Unit::TestCase
def setup
# NameError: uninitialized constant Expressions::DATE here:
@expression = Expressions::DATE
end
def test
assert "1970-01-01" =~ @expression
end
end
This produces an NameError: uninitialized constant Expressions::DATE error.
I know I could just define attributes on a class to be used as an instance, but this is inefficient and not a correct solution to the problem (just a hack). (In C++ I would use a static const, done)
So I'm stuck really. I need to know what is the correct way in Ruby to define constant regular expressions that need to be used in other classes. I'm having a problem with the definition, initialisation and its use,
thanks.