I'm trying to write a utility library which tries to call a method on an arbitrary object type. In ruby, I'd do something like:
def foo(object)
object.public_send(:bar)
rescue NoMethodError
raise "Method not defined on object"
end
foo(instance_of_my_arbitrary_class)
I'm not sure how to do this in Crystal, as the type us unknown so I get a compiler error of Can't infer the type of instance variable 'object'
.
How do I accomplish this without knowing the type of the object which will be passed?
I think I figured this out after by utilizing a module and including it.
module ArbitraryObject; end
class Arbitrary
include ArbitraryObject
end
class MyLib
def foo(object : ArbitraryObject)
... Code here ...
end
end
MyLib.new(Arbitrary.new).foo