defined

Conditional compilation based on constants, version requirements, and environment
0.3.0 released

defined

Defined.cr CI GitHub release GitHub commits since latest release (by SemVer)

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

  1. Add the dependency to your shard.yml:

    dependencies:
      defined:
        github: wyhaines/defined.cr
    
  2. 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

  1. Fork it (https://github.com/wyhaines/defined/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

GitHub code size in bytes GitHub issues

defined:
  github: wyhaines/defined.cr
  version: ~> 0.3.0
License MIT
Crystal *

Authors

Dependencies 0

Development Dependencies 1

  • ameba ~> 0.14
    {'github' => 'crystal-ameba/ameba', 'version' => '~> 0.14'}

Dependents 0

Last synced .
search fire star recently