indus
indus

Reputation: 103

creating link_to using regex from a comment

I'm trying to create a helper that finds any thing that starts with a # that has numbers afterwards separated by spaces, then remove the #, and turn it into a link.

However I'm not entirely sure what I'm doing wrong, right now the comment is appearing blank.

How can I do this correctly?

So far I have:

module ApplicationHelper
    def linkhelper (comment)
        link = comment.to_s.gsub (/a?#\d.*\d/)
        if Post.friendly.exists?(@link)
            boardid = self.board_id
            postid = link
            link_to "#link", boardid.postid, :anchor => link
        elsif Reply.exists?(:pid => @link)
            boardid = self.board_id
            postid = reply.link.post_id
            link_to '#link', boardid.postid, :anchor => link
        else '#link'
        end
    end
end

In my view:

<% linkhelper(post.comment) %>

Update:
Currently my site is set up like this: board has many posts, and each post has many replies. When a post is made it checks what the highest pid is between all posts and replies for that board, and sets it maximum pid + 1.

What I'm trying to do is:

match #123, remove the #

If it matches any Post.pid get post.board_id, replace #123 with a link_to #123, board_id/123.

elsif if it matches any Reply.pid get reply.post_id and reply.board_id. replace #123 with link_to #123, board_id/post_id#123.

else just put #123.

The code I ended up using:

def linkhelper(comment)
  comment.to_s.gsub (/#(\d+)+/) do |match|
    slug = $1.strip
    if (post = Post.friendly.find_by(pid: slug))
      link_to ">>#{slug}", "#{post.board_name}/thread/#{slug}##{slug}"
    elsif (reply = Reply.find_by(pid: slug.to_i))
      link_to "##{slug}", "#{reply.board_name}/thread/#{reply.post_pid}##{slug}"
    else
      "##{slug}"
    end
  end
end

Upvotes: 1

Views: 76

Answers (1)

Michael Gaskill
Michael Gaskill

Reputation: 8042

This should be close to what you're trying to do:

def linkhelper(comment)
  link = comment.to_s.gsub (/#(\d+)\s+/) do |match|
    slug = $1.strip
    if (post = Post.friendly.find_by(id: slug))
      link_to "##{slug}", "#{post.board_id}/#{slug}"
    elsif (reply = Reply.friendly.find_by(pid: slug.to_i))
      link_to "##{slug}", "#{reply.board_id}/#{reply.post_id}##{slug}"
    else
      "##{slug}"
    end
  end
end

This uses gsub with a block to allow you great control over what gets replaced, so the link_to should contain the link that you expect.

Upvotes: 1

Related Questions