I have a helper class defined as follows:
require "toml"
module Test
class Utils
@@config
def self.config
if @@config.is_a?(Nil)
raw_config = File.read("/usr/local/test/config.toml")
@@config = TOML.parse(raw_config)
end
@@config
end
end
end
When I call this method elsewhere in the code:
server = TCPServer.new("localhost", Utils.config["port"])
I receive the following compile-time error:
in src/test/daemon.cr:10: undefined method '[]' for Nil (compile-time type is (Hash(String, TOML::Type) | Nil))
server = TCPServer.new("localhost", Utils.config["port"])
There is no way for Utils.config
to run something that is Nil
, so I don't understand the error.
- How do I tell the compiler
Utils.config
will always return something that is notNil
? - (Minor additional question) Is this a good design pattern for a resource (the
config
) that will be shared between classes, but only should be created once?