Search code examples
rubytddguard

What is the significance of m[1] in a Guardfile?


From Guardfile examples:

watch(%r{^app/(.+)\.rb})    { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^lib/(.+)\.rb})    { |m| "spec/lib/#{m[1]}_spec.rb" }

What do the values of m represent? It seems to be an array of length 2, storing the complete path and relative path...

How is m generated? Is it coming from Guard or Ruby?


Solution

  • m[1] would be the first capture group in the regex match. And from the regex, that is the name of the file ( without the extension.)

    This is actually explained in the README:

    guard :rspec do
      watch(%r{^lib/(.+)\.rb$})     { |m| "spec/lib/#{m[1]}_spec.rb" }
    end
    

    In this example the regular expression capture group (.+) is used to transform a file change in the lib folder to its test case in the spec folder. Regular expression watch patterns are matched with Regexp#match.