Here’s a bit of code that I both love and feel a bit guilty about.
project_root = Pathname.pwd.ascend{|dir| break dir if (dir + "demos").directory? } or fail "No project root found"
This code locates a project’s “root directory” by ascending from the current directory until it finds a directory with a subdirectory named demos
. (Don’t ask why this indicates the root directory). In case it never finds such a directory, it raises an exception.
Love, because it’s so expressive and uses so many of my favorite Ruby goodies.
Guilt, because it’s dense and not the most revealing code in the world. Nothing about it is “tricky” or obfuscated; it just packs a lot into a small space.
Ruby goodies featured in these three lines include:
- Pathname (covered in RubyTapas #193)
- Pathname#ascend (covered in RubyTapas #60)
- break with a value (covered in RubyTapas #071)
- A statement modifier ( if )
- English or used as intended for trailing control flow (episode #125)
- fail to indicate a failure, per Jim Weirich (see RubyTapas episode #188)
My variant looks like this:
project_root = Pathname(dir)
.to_enum(:ascend)
.detect(lambda { fail “Nope” }) { |dir| (dir + ‘demos’).directory? }
What really bugs me is the #to_enum (064 Yield or Enumerate)
this bold dir should be underscore-underscore-dir-underscore-underscore