At first glance, it seems that embedding a template inside another template will just work, but based on a bad assumption about how templates work in Ruby, they are just strings. Using:
foo_regex = /foo/
creates a regexp object:
/foo/.class
As such, he knows the additional flags used to create it:
( /foo/ ).options
or if you like the binary:
'%04b' % ( /foo/ ).options
and remembers them whenever Regexp is used, whether it's a separate template or built-in to another.
This can be seen in action if we look at how the template looks after implementation:
/#{ /foo/ }/
?-mix: and ?i-mx: :: how these options are presented in the built-in template.
According to the Regexp documentation for Options :
i , m and x can also be applied at the subexpression level with a (? on-off) construct that enables options and disables options for an expression enclosed in parentheses.
So, Regexp remembers these parameters, even inside the external template, forcing the common template to fail to match:
pattern = /A
You can make sure that all subexpressions match their surrounding patterns, however this can quickly become too confusing or messy:
foo_regex = /foo/i pattern = /A #{ foo_regex }/i
Instead, we have a source method that returns the text of a template:
/#{ /foo/.source }/
The problem with the built-in template that remembers the parameters also appears when using other Regexp methods, such as union :
/#{ Regexp.union(%w[ab]) }/
and again source can help:
/#{ Regexp.union(%w[ab]).source }/
Knowing all this:
foo_regex = /foo/ pattern = /#{ foo_regex.source }/i