guard
Version, currently 1.0.11 version
- 1.0.1latestJun 12, 2026
github.com/plambert/guard.cr
Easy to read assertions for truthiness or non-nil values
Installation
# Add this to your shard.yml
dependencies:
guard:
github: plambert/guard.cr
version: ~> 1.0.1Then run:
shards installshard.yml
- Crystal
>= 1.0.0- License
- MIT
- Author
- Paul M. Lambert
Dependencies
This version declares no dependencies.
README
guard
Simple assertion macros to make code a little clearer.
Why? The static code analysis tool ameba has a rule called Style/GuardClause
which is described as “Check for conditionals that can be replaced with guard clauses.”
It’s a generally good idea; for example, instead of writing this:
def my_method
if thing = @thing
# use thing
end
end
the tool recommends this:
def my_method
return unless thing = @thing
# use thing
end
which makes a lot of sense to me. However, at the time of this writing, the rule is disabled by default in ameba. I don't know why, but for me, I would disable it because having an assignment on the right of an inline conditional like that is hard to read—at least, I know it’s hard to read for me.
So I wrote guard which you use like this:
class MyClass
include Guard
def my_method
thing = guard @thing
# use thing
end
end
That’s it—just put guard in front of the value in the assignment, and if the value is
false or nil then the macro will return nil from the method immediately.
If instead you want to raise an exception, create an Exception in a block:
class MyClass
include Guard
def my_method
thing = guard @thing { MyException.new %["oh bother," said Eeyore, "there is no thing there"] }
# use thing
end
end
And finally, if you only want to guard against nil values, but leave false alone,
then you can use the guard! variants.
class MyClass
include Guard
@thing = false
def my_method
thing = guard! @thing
# use thing, even if it’s `false`
end
end
Installation
-
Add the dependency to your
shard.yml:dependencies: guard: github: plambert/guard.cr -
Run
shards install
Usage
require "guard"
class MyClass
include Guard
end
Development
TODO: Write development instructions here
Contributing
- Fork it (https://github.com/plambert/guard.cr/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
- Paul M. Lambert - creator and maintainer
Documentation
Built from the current release. The first visit to a release nobody has asked for starts its build.
Links
This release
- Version
1.0.1- Tagged
- Jun 12, 2026
- Commit
ab10ca32d4e8- Crystal
>= 1.0.0- Indexed
- yes
Dependents
Repository
github.com/plambert/guard.cr
Metadata
- Created
- Aug 12, 2026
- Updated
- Aug 17, 2026
- Synced
- Aug 17, 2026
- Versions
- 1