Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using simple_hashtag gem to link to hashtags in model's 'body' attribute

Sorry for the vague title

I'm using rails 4 and the simple_hashtag gem (https://github.com/ralovely/simple_hashtag). I have it working great, but I want to go a little further. Right now my post model has a description attribute and if a user precedes a word with a hashtag (#), then that post has hashtags and you can show them with

@post.hashtags.each do |hashtag|
  link_to hashtag.name, path_to_hashtag(hashtag.name)
end

these hashtags then become links so you can search all of the posts with the given hashtag. Unfortunately, when you show the post's description, it shows it with the hashtags in it as plain text, not links. I'd rather just turn the post's descriptions hashtags into links (Twitter does this)..Does anyone know how i can do this??

like image 323
Justin Avatar asked Oct 20 '22 22:10

Justin


1 Answers

Looks like I had not run the generator to get the views. With this generator, you get the hashtag helper file which includes this method.

def linkify_hashtags(hashtaggable_content)
  regex = SimpleHashtag::Hashtag::HASHTAG_REGEX
  hashtagged_content = hashtaggable_content.to_s.gsub(regex) do
    link_to($&, hashtag_path($2), {class: :hashtag})
  end
  hashtagged_content.html_safe
end

That's the method to use to get the hashtags to turn into links.

like image 67
Justin Avatar answered Oct 24 '22 00:10

Justin