Rails 4: how to identify and format links, hashtags and mentions in model attributes?
I'm sure each of the following regex patterns could be improved to match even more options, however, the following code works for me:
def highlight_url(str)
str.gsub!(/(https?:\/\/[\S]+)/, '[\1]')
end
def highlight_hashtag(str)
str.gsub!(/\S*#(\[[^\]]+\]|\S+)/, '[#\1]')
end
def highlight_mention(str)
str.gsub!(/\B(\@[a-z0-9_-]+)/i, '[\1]')
end
# Initial string
str = "Myself and @doggirl bought a new car: http://carpictures.com #nomoremoney"
# Pass through each
highlight_mention(str)
highlight_hashtag(str)
highlight_url(str)
puts str # > Myself and [@doggirl] bought a new car: [http://carpictures.com] [#nomoremoney]
In this example, I've wrapped the matches with brackets []
. You should use a span
tag and style it. Also, you can wrap all three gsub!
into a single method for simplicity.
Updated for the asker's add-on error question
It looks like the error is references another method named highlight
. Try changing the name of the method from highlight to new_highlight
to see if that fixes the new problem.
Ruby on Rails - Converting Twitter @mentions, #hashtags and URLs within a string
The twitter-text gem has pretty much all the work covered for you. Install it manually (gem install twitter-text
, use sudo if needed) or add it to your Gemfile (gem 'twitter-text'
) if you are using bundler and do bundle install
.
Then include the Twitter auto-link library (require 'twitter-text'
and include Twitter::Autolink
) at the top of your class and call the method auto_link(inputString)
with the input string as the parameter and it will give you the auto linked version
Full code:
require 'twitter-text'
include Twitter::Autolink
myString = "I like using @twitter, because I learn so many new things! [line break]
Read my blog: http://www.myblog.com #procrastination"
linkedString = auto_link(myString)
If you output the contents of linkedString, you get the following output:
I like using @<a class="tweet-url username" href="https://twitter.com/twitter" rel="nofollow">twitter</a>, because I learn so many new things! [line break]
Read my blog: <a href="http://www.myblog.com" rel="nofollow">http://www.myblog.com</a> <a class="tweet-url hashtag" href="https://twitter.com/#!/search?q=%23procrastination" rel="nofollow" title="#procrastination">#procrastination</a>
Using simple_hashtag gem to link to hashtags in model's 'body' attribute
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.
Looking for a rails gem or method to search by hashtags and reply to posts by tagging user with @
I have been developing a similar thing some time ago and i don't think that there are such gems available for the things you need. It's too complex to be handled by a gem. If you want it to work in a similar manner to twitter, here is how i would do that:
1. Posts tagging
Let's say we have a Post
model with body
param. First, to add a tagging functionality, we should enable acts_as_taggable_on
gem for our Post
model which will give us few methods, like tag_list
for instance. When that's ready, we need to somehow obtain hashtags provided in a body
field and save them as tag_list
.
My solution for that was to use a twitter-text-rb gem. Using a following code snippet, you can extract hash tags from a body
field and save them to tag_list
.
def extract_tags(post)
include Twitter::Extractor
tags = extract_hashtags(post.body)
post.update_attribute(:tag_list, tags)
end
And from that point, we're able to search for posts tagged with certain tags using acts_as_taggable_on
built-in methods Post.tagged_with('#first')
2. Users mentioning
I've never been doing such thing but as i can see, the twitter-text-rb
gem also helps with extracting mentions. I'm also not sure what you're trying to accomplish and how that exactly should work but knowing that the previously mentioned gem can help you with extracting mentions and knowing how to deal with tags, it should not be a big deal for you to deal with that ;)
Hope that helps
Is there a proper way to highlight # hashtags and @ users in text?
More details would be helpful.
you could catch them with regex.
Learn regular expressions. They're worth your time.
http://rubular.com/
http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UJ
You didn't tag this with HTML, but that sounds like a large aspect of what you're asking.
turning hashtags to link but ignoring the urls fragment Identifiers
This one made the work:
(?<=\W)#(\w+)
http://www.phpliveregex.com/p/b1u
Rails 4: helper method working locally, breaking on Heroku
I found the root cause of the problem.
I launched IRB in Terminal an ran a few tests:
h = "hello"
h.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight">\1</span>')
# => nil
l = "http://www.link.com"
l.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight">\1</span>')
# => "<span class=\"highlight\">http://www.link.com</span>"
The problem actually happens when the string I am trying to highlight DOES NOT contain any of the patterns we are looking for with the regex.
To fix the issue, I had to replace .gsub!
with .gsub
, and implement conditional statements, so that the method returns the initial string unchanged when no pattern was detected, instead of nil.
This is my new posts_helper.rb
:
module PostsHelper
def link_highlight(string)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight">\1</span>')
if result1.nil?
init1
else
result1
end
end
def hashtag_highlight(string)
init2 = string
result2 = string.to_s.gsub!(/\S*#(\[[^\]]+\]|\S+)/, '<span class="highlight">#\1</span>')
if result2.nil?
init2
else
result2
end
end
def mention_highlight(string)
init3 = string
result3 = string.to_s.gsub(/\B(\@[a-z0-9_-]+)/i, '<span class="highlight">\1</span>')
if result3.nil?
init3
else
result3
end
end
def new_highlight(string)
link_highlight(string)
hashtag_highlight(string)
mention_highlight(string)
end
end
This may not be the cleanest / leanest code, but it works — both locally and remotely — and it allows me to chain all three methods in the new_highlight
final method.
Deleting tag element from Rails database when certain tag is no longer used in any post
One way I created tagging was to create a Tag
model and table, and then a Taggings
model and table.
tag.rb
class Tag < ApplicationRecord
has_many :taggings
has_many :posts, through: :taggings
end
tagging.rb
class Tagging < ApplicationRecord
belongs_to :tag
belongs_to :post
end
post.rb
class Post < ApplicationRecord
has_many :taggings
has_many :tags, through: :taggings
end
So now you just have the join table that uses a post_id and tag_id to join the two. This way you can enforce uniq
on your tag table to avoid redundant tags. As mentioned above you could build an after_destroy
method that deletes a tag after checking to see if it is used anywhere else. Or like Dave Newton mentioned keep it around for historic purposes for autocomplete suggestions.
Twitter share button not using custom url or text
The code provided by you is perfectly fine and should work as expected.
Many site issues can be caused by corrupt cookies or cache. Try to clear both cookies and the cache. I would suggest you to look into the following link to see why it is not working in firefox
Related Topics
How to Use The Auto Value with The Calc() Property
Center Text in HTML Number Input
Div Scrollbar - Any Way to Style It
Using Section Element for Stylistic Layout and Wrappers
HTML5 & Bootstrap Class="Container", Can It Be Applied to Body or Only Div
CSS: Placing Divs Left/Center/Right Inside Header
Div Not Expanding Even with Content Inside
Radio Button Show/Hide Content
Changing The Style of Radio Buttons in Jquery Mobile 1.4.0
How to Specify The System's Default Serif and Sans-Serif Font-Family
Can The SASS Minifier Remove Duplicate Styles
How to Use Div Class and Id Together in CSS
CSS3/HTML 5/Png Blur Content Behind Element
How to Style The Input Type "Time"
Div Moves When I Put Text in It