开发者

Ruby/Rails: How can I replace a string with data from an array of objects?

I have two bits of data I'm working with here.

A "question": This is an [example] string for [testing] and [what not].

And then I have an array of objects (called "answers") from my database:

[#<Answer id: 137, question_id: 207, text: "example">, #<Answer id: 138, question_id: 207, text: "testing">, #<Answer id: 139, question_id: 207, text: "what not"]

What I need to d开发者_开发问答o is replace the bracketed text in the question ([example]) with a link containing data from the corresponding object.

So [example] might become <a href="#" data-answer="137" data-question="207">example</a>.

How can I do that?


Assuming you have the answers already:

str = "This is an [example] string for [testing] and [what not]."
answers.each{|o| str.gsub!("[#{o.name}]", "<a href=\"#\" data-answer=\"#{o.id}\" data-question=\"#{o.question_id}\">#{o.name}</a>")}

If you don't have the answers:

str = "This is an [example] string for [testing] and [what not]."
m =  str.scan(/\[([^\]]*)\]/).map{|s|s[0]}
Answer.where(:text => m).each{|o| str.gsub!("[#{o.name}]", "<a href=\"#\" data-answer=\"#{o.id}\" data-question=\"#{o.question_id}\">#{o.name}</a>")}

This works by using regex to search for all the text inbetween the [] brackets, which then returns an array to m. This array consists of ["example", "testing", "what not"].

You then pass that array into the where() call, which internally has SQL use an IN expression, such as WHERE text IN ('example','testing', 'what not')

After running this, str is now changed to your desired result.


If you don't want to have to get the whole table from the database, you can search for those bracketed strings first, then perform a search on the database:

str = "This is an [example] string for [testing] and [what not]."
matches =  str.scan(/\[([^\]]*)\]/).collect { |s|s[0]}
Answer.where( :text => matches).each{|o| str.gsub!("[#{o.name}]", "<a href=\"#\" data-answer=\"#{o.id}\" data-question=\"#{o.question_id}\">#{o.name}</a>")}


s = "This is an [example] string for [testing] and [what not]"
 => "This is an [example] string for [testing] and [what not]" 
h = {id: 137, question_id: 207, text: "example"}
 => {:id=>137, :question_id=>207, :text=>"example"} 

s.sub(/\[example\]/, %Q{<a href="#" data-answer="#{h[:id]}" data-question="#{h[:question_id]}">#{h[:text]}</a>})
 => "This is an <a href=\"#\" data-answer=\"137\" data-question=\"207\">example</a> string for [testing] and [what not]" 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜