I should preface this by saying that I like Ruby: it allows you to express both powerfully and tersely. But to be trite, with great power... well, you know the rest. As for RubyOnRails: I haven't gotten around to using it but a lot of people have and like it very much. Being Open Source, there are supposed to be a lot of people watching. Fabian is one of those people.

He sends us the following single like of source code, broken into multiple lines for your viewing pleasure. Watch, in amazement, as we dissect a RegexpInRuby.

This code is from the "Engines" plug-in for RubyOnRails and according to Fabian, "It's copied-and-abused from an original function in Rails, where using RE makes actually sense."

  base.match(/^#{ActionController::Routing.controller_paths.map { |p|
File.expand_path(p) } * '|'}/)

 

What's it do? Let's break it down. Apparently, ActionController::Routing has a variable that contains file-system paths. The map normalizes and resolves those paths to canonical paths. The strings in this new array are joined by the pipe symbol and the monstrosity is appended to a carrot and turned into a regular expression. The variable base is matched against this expression. The developer probably intended to ask: "Is the string base among the canonicalized paths for ActionController::Routing?"

Fabian continues:

One should appreciate the "^" at the beginning of the RE. It is probably supposed to ensure that base does not match only a part of a path entry. Unfortunately it would do that only for the first entry, if not the match function would already ensure a complete match from beginning to end.

 

Is there an easier way to do this? Using /RE/.match(base) would probably be a start. To take care of two problems, do away with regular expressions altogether and use the built-in include?, e.g.

  ActionController::Routing \
      .controller_paths \
      .map { |p| File.expand_path(p) } \
      .include?(base)

 

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!