I am working with a library which uses strings as ids throughout. I want to make a class which can be used in place of these ids, but looks like a string to the existing code. E.g. I have an existing test which looks like this:
require 'test/unit'
class IdString < Hash
def initialize(id)
@id = id
end
def to_s
@id
end
end
class TestGet < Test::Unit::TestCase
def test_that_id_is_1234
id = IdString.new('1234')
assert_match(/1234/, id)
end
end
Unfortunately this fails with:
TypeError: can't convert IdString to String
Is there a way to fix this without changing all the existing code which expects ids to be strings?
You should implement to_str method, which is used for implicit conversions:
def to_str
@id
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With