I was looking over Michael Hartl's online book and came across this regex line for his Guardfile
.
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) do |m|
["spec/routing/#{m[1]}_routing_spec.rb",
"spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb",
"spec/acceptance/#{m[1]}_spec.rb",
(m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" :
"spec/requests/#{m[1].singularize}_pages_spec.rb")]
What does the last bit do:
(m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" :
"spec/requests/#{m[1].singularize}_pages_spec.rb")]
)
I get that m[1]
would be the name of the controller, but what does the [/_pages/]
part accomplish?
You can use a regex on to get a substring out of a string. It returns the first match or nil
if no matches are found.
string = "foobar"
string[/[ab]/] # => "b"
string[/ab/] # => nil
However, Michael uses it as a simple check if the regex matches. You might have seen it written with the =~
operator:
m[1] =~ /_pages/ ? something : something_else