I'm creating a Twitter clone in Ruby On Rails, how can I encode it so that "@ ..." in "tweets" turns into links?

I'm kind of new to Rails, so carry with me, I have most of the application except for this one part.

+3
source share
7 answers
def linkup_mentions_and_hashtags(text)    
  text.gsub!(/@([\w]+)(\W)?/, '<a href="http://twitter.com/\1">@\1</a>\2')
  text.gsub!(/#([\w]+)(\W)?/, '<a href="http://twitter.com/search?q=%23\1">#\1</a>\2')
  text
end

I found this example here: http://github.com/jnunemaker/twitter-app

Link to helper method: http://github.com/jnunemaker/twitter-app/blob/master/app/helpers/statuses_helper.rb

+5
source

Perhaps you could use regular expressions to search for "@ ..." and then replace the matches with the appropriate link?

0

@sometext {whitespace_or_endofstring}

0

, , , :

Regex.Replace("this is an example @AlbertEin", 
                    "(?<type>[@#])(?<nick>\\w{1,}[^ ])", 
                    "<a href=\"http://twitter.com/${nick}\">${type}${nick}</a>");

this is an example <a href="http://twitter.com/AlbertEin>@AlbertEin</a>

.NET

(?<type>[@#])(?<nick>\\w{1,}[^ ]) , TYPE , @ #, NAME , , .

0

, , @, .

, @, , , :

\@[\S]+\
0

You would use a regular expression to search for the @username name and then change it to the appropriate link.

I use the following for @ in PHP:

$ret = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", 
                    "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", 
                    $ret);
0
source

I am also working on this, I'm not sure if it is 100% perfect, but it seems to work:

  def auto_link_twitter(txt, options = {:target => "_blank"})
    txt.scan(/(^|\W|\s+)(#|@)(\w{1,25})/).each do |match|
      if match[1] == "#"
        txt.gsub!(/##{match.last}/, link_to("##{match.last}", "http://twitter.com/search/?q=##{match.last}", options))
        elsif match[1] == "@"
          txt.gsub!(/@#{match.last}/, link_to("@#{match.last}", "http://twitter.com/#{match.last}", options))
          end
    end
    txt
  end

I put it together with a google search and some reading on String.scan in api docs.

0
source

Source: https://habr.com/ru/post/1727879/


All Articles