解析@username的post

我已经建立了类似Twitter的@replies,允许用户通过用户每日邮件相互联系…类似于stackoverflow。

以此为指导https://github.com/kltcalamay/sample_app/compare/original-version…master

如何解析/扫描post,然后将@usernames替换为该用户页面的链接

post的例子。

Kevins Post: @Pzpcreations @john @steve hey everyone lets all hang out today 

我想扫描/解析post,然后将用户@Pzpcreations @john @steve链接到他们的个人资料

我尝试在Dailypost模型中创建一个方法,将用户名存储在数组中….但IDK如何替换并将它们链接到相应的用户页面

 def username_link str = self.content_html recipient = str.scan(USERNAME_REGEX) end 

这给了我[“@Pzpcreations”,“@ john”,“@ step”]

请帮帮我….新到铁路:)

楷模

 class Recipient < ActiveRecord::Base attr_accessible :dailypost_id, :user_id belongs_to :user belongs_to :dailypost end class User  'Recipient', :dependent => :destroy has_many :received_replies, :through => :replies, :source => 'dailypost' end class Dailypost  :recipients, :source => "user" after_save :save_recipients **private** def save_recipients return unless reply? people_replied.each do |user| Recipient.create!(:dailypost_id => self.id, :user_id => user.id) end end def reply? self.content.match( USERNAME_REGEX ) end def people_replied users = [] self.content.clone.gsub!( USERNAME_REGEX ).each do |username| user = User.find_by_username(username[1..-1]) users << user if user end users.uniq end end 

SCHEMA

 create_table "recipients", :force => true do |t| t.string "user_id" t.string "dailypost_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end [#] User_ID in recipients are the users that are mentioned in the Dailypost. 

VIEWS

  

您可以将每个匹配传递到一个块。 在这个块中,您将返回所需的链接,例如

 def username_link str = self.content_html str.gsub!(USERNAME_REGEX).each do |recipient| if User.find_by_name(recipient) "[link to #{recipient}]" else recipient end end end 

编辑

app/helpers/posts_helper.rb创建一个辅助函数

 def post_with_links(post) post.content_html.gsub(/@\w+/).each do |username| user = User.find_by_username(username[1..-1]) if user link_to username, user else username end end 

在你的视图中使用它

 <%= post_with_links(post) %> 

您希望在每个用户名上进行查找和替换,并生成指向用户配置文件的链接。 它看起来像这样:

 def username_link new_content_html = self.content_html recipients = new_content_html.scan(USERNAME_REGEX) recipients.each do |recipient| user = User.find_by_username(recipient) # strip off the @ if required new_content_html.gsub!(recipient, "#{user.username}") end new_content_html end 

这假设您在路由文件中为users了生成users_path方法的路由。

还有一个完整的兔子洞需要讨论,因为它会像推特一样回复系统,而发现自己的那些将是一半的乐趣! ;)