Suppose I have a body of text (string) like this:
str = ‘This is some text. {insertion_1} And this is also some text. {insertion_2}’
The contents of the two curly braces represent a model (Insertion) and its ID. The ultimate goal is to parse the string, and replace the curly braced “insertions” with an insertion partial. The insertion partial will simply be a line or two of HTML.
If the insertions were static I could do something like str.gsub!(/\{insertion_\d*\}/, 'some content'), but I need to parse the insertions one-by-one, to insert the appropriate data. Can anyone suggest a best practice for handling a situation like this?
EDIT: I should have mentioned, this is for a WYSIWYG. The end user selects from a list of “insertions” and once selected, it adds the appropriate {insertion_id} placeholder into the body of their post, which will be parsed out later to insert the right content.
You can use regexp captures and
gsubwith a block to accomplish what you want, like this:Just replace the block body with whatever you need to do. 🙂
(Sidenote:
\d+is a better choice than\d*for matching numbers.)