LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】特定の文字列をリンクにする

Last updated at Posted at 2020-01-16

運営しているサイトの掲示板において、返信時、冒頭に>>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という記述があると、関数で文字列を操作することができずエラーになってしまうので注意です。

参考

文字列の一部を削除する
戻り値が複数ある場合の変数代入

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0