Katie H
Katie H

Reputation: 2293

User tagging auto linking - Rails

In my rails app. I am trying to write a helper that auto_links the mention of a "@someusername" in a comment and link to user_path("@someusername").

How can I do this?

Can I just customize the auto_link helper?

Upvotes: 3

Views: 1167

Answers (3)

JesWang
JesWang

Reputation: 21

This one works better, \b is word break detection, so the sentence could be just @username and nothing else, and it will still work (white space and , are also considered as word break).

def auto_link_usernames(text)
  text.gsub /(?<=\s|^)@[A-Za-z0-9_]+(?=\b)/ do |username|
  link_to(username, user_path(username.gsub('@', '')))
  end.html_safe
end

Upvotes: 2

Ismael
Ismael

Reputation: 16730

That seems pretty easy to do.

def auto_link_usernames(text)
  text.gsub /@(\w+)/ do |username|
    link_to(username, user_username_path(username.gstub('@', '')))
  end.html_safe
end

You need to add a new route and controller action so you can have user pages with usernames like /user/:username

In your controller you would do

def username_show
  @user = User.where(username: params[:username]).first
  render 'show'
end

Edit:

Actually this works perfectly:

def auto_link_usernames(text)
  text.gsub /@(\w+)/ do |username|
    link_to(username, user_path(username.gsub('@', '')))
  end.html_safe
end

Upvotes: 5

Matt
Matt

Reputation: 10564

Looking at the gem in which auto_link has been extracted from Rails 3.1+, it appears that they didn't think of auto_link as being extensible. Line 64 shows a case statement where they call methods specific to each type of autolinking, so you'll have to add your new method here if you want it to be picked up.

If I were you, I would fork this gem from Github and modify it's source. This presumes you're using Rails 3.1+. You can even submit a pull request to the gem maintainers to see if they want to add in this functionality.

If you're not using the gem or don't want to fork a git repo, I suppose I would monkey-patch it like this: I would create my own helper, called ReferenceAutolink or some such, make it extend ActionView::Helpers::TextHelper, and place it in your app's helpers as you would any other helper. I'm pretty sure that application helpers can override existing helpers when you call helper_method, so I would simply copy and paste the existing auto-link code into this helper and add another method to delegate to in the case statement which handles your referencing links. You'll have to rewrite the whole case statement, because it appears they cascade method calls in order to determine precedence.

It's a bit gross, but doable.

Upvotes: 1

Related Questions