简体   繁体   English

Ruby on Rails .gsub正则表达式并渲染部分

[英]Ruby on Rails .gsub regex and render partial

I have a series of some strings, that i want to convert to render-partial. 我有一些字符串,我想转换为render-partial。

For example. 例如。 I have a @post.content, which contains 我有一个@ post.content,其中包含

Lopem ipsum dolor sic amet *form_34e141443439d1000000* Lorem dolorem *form_f97391de6275724201000000* Lopem ipsum dolor sic amet * form_34e141443439d1000000 * Lorem dolorem * form_f97391de6275724201000000 *

Which i want to process. 我想要处理哪个。

I tried 我试过了

content.gsub(/\*form_(.*?)\*/, render(partial: 'forms/render_form', object: CustomForm.where(_id: '\1').first, as: 'form_item'))

But that does not do anything correct, results only in "undefined local variable or method `form_item' for #<#:0xb53a2810>" error. 但是这没有做任何正确的事情,结果只是“未定义的局部变量或方法`form_item'##:#0xb53a2810>”错误。

But if i try 但是,如果我尝试

content.gsub(/\*form_(.*?)\*/, render(partial: 'forms/render_form', object: '\1', as: 'form_item'))

and try <%= form_item %> in partial, it returns to me an correct value - f97391de6275724201000000 在partial中尝试<%= form_item%>,它会返回给我一个正确的值 - f97391de6275724201000000

and if i try 如果我试试

content.gsub(/\*form_(.*?)\*/, render(partial: 'forms/render_form', object: CustomForm.where(_id: 'f97391de6275724201000000').first, as: 'form_item'))

it works just like i want it to - gets me a form model to process. 它就像我想要的那样工作 - 让我得到一个表格模型来处理。

QUESTION: 题:

How do i throw \\1 value from /*form_(.*?)*/ regexp to CustomForm.where(_id: '\\1').first ? 我如何将/ * value_(。*?)* / regexp中的\\ 1值抛出到CustomForm.where(_id:'\\ 1')。

You can use the block form of the gsub method where the pattern match is available as the $1 variable: 您可以使用gsub方法的块形式,其中模式匹配可用作$1变量:

content.gsub(/\*form_(.*?)\*/) do |match|
  render(partial: 'forms/render_form', 
         object: CustomForm.where(_id: $1).first, as: 'form_item'))
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM