運営しているサイトの掲示板において、返信時、冒頭に>>123
のような記述が入るようにしているのですが、この部分をその番号のコメントへのリンクにすることができたので、やり方を書き残しておきます。
controller
app/controllers/comments_controller.rb
def index
@comments = Comment.all
end
hepler
app/helpers/comments_helper.rb
module CommentsHelper
def generate_link(txt)
reply_txt = txt.slice(/>>[0-9]+/)
id = reply_txt.slice(/[0-9]+/)
link = ''
link << "<a href='" << "##{id}'>#{reply_txt}</a>"
content = txt.sub!(/>>[0-9]+/, '')
[link: link, content: content]
end
end
テキスト内の>>{数字}
を抜き出して、aタグに変えて、他の文章と分離させた状態で値を返す処理をしています。
view
app/views/comments/index.html.erb
<% @comments.each do |i| %>
<% if i.content.slice(/>>[0-9]+/) %>
<% reply = generate_link(i.content)[0] %>
<%= reply[:link].html_safe %><br><%= reply[:content] %>
<% else %>
<%= i.content %>
<% end %>
<% end %>
.html_safe
を利用しないと、<a href="hogehoge"
等がそのまま表示されてしまいます。
注意点
helper関数を記述するファイルの冒頭に# frozen_string_literal: true
という記述があると、関数で文字列を操作することができずエラーになってしまうので注意です。