defined
defined
This is a very small shard that provides a single macro, defined?(), which returns VALUE/false depending on whether the argument provided points to an existing constant. All lookups start at the top level and descend from there.
Installation
-
Add the dependency to your
shard.yml
:dependencies: defined: github: wyhaines/defined.cr
-
Run
shards install
Usage
require "defined"
if defined?("OptionalFeature")
# The OptionalFeature library has been included into the code, so use it.
else
# It's not there.
end
stuff = defined?("My::Stuff::Library") || Array(String)
Crystal does not permit dynamic creation of classes, and it has compile time checks which happen before macros are evaluated to catch these cases and error on them. So, if one wants to dynamically create classes, it requires a bit of a workaround:
require "defined"
class One; end
if_defined?("One", <<-ECODE)
class Two
def call
"I am class Two, but I can only exist of class one is defined."
end
end
ECODE
puts Two.new.call
One use case might be, in a library, to provide packaged functionality if a given library was not required elsewhere in the code:
unless_defined?("PerfectShard", <<-END)
require "project/imperfect_shard"
END
Contributing
- Fork it (https://github.com/wyhaines/defined/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- Kirk Haines - creator and maintainer