Reputation: 67
I am working on the normal rails blog app, I need to add a tag feature (the same tag as every social media uses).
Example of post: "I love #dogs". What I need to do is to display the tag #dogs
as a link_to dogs_path
. Any ideas?
Upvotes: 0
Views: 176
Reputation: 26091
You can use a regex to scan the string and extract hastags
source = 'Lets #go to the #gym #today'
hashes = source.scan /\B#[á-úÁ-Úä-üÄ-Üa-zA-Z0-9_]+/
puts hashes
see it at replit
class SocialHelper
def linked_content(source)
hashes = string.scan(/\B#[á-úÁ-Úä-üÄ-Üa-zA-Z0-9_]+/)
hashes.each do |hash|
source.gsub!(hash, hash_link(hash)
end
source
end
def hash_link(hash)
link_to hashes_path(hash)
end
end
<%= linked_content(post.content) %>
Upvotes: 1
Reputation: 1186
You can make a link out of text with this ERB in your HTML file: <%= link_to "#dogs", dogs_path %>
Where the string immediately following the link_to
is the string that will be populated as text on the page (a hyperlink).
For your case, you could do something like:
<p>I love <%= link_to "#dogs", dogs_path %>.</p>
Upvotes: 0