Ruby Guilty Pleasures

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:

2 comments

  1. 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)

Comments are closed.