diff --git a/app/logical/d_text.rb b/app/logical/d_text.rb index 1326e4497..39daefbb1 100644 --- a/app/logical/d_text.rb +++ b/app/logical/d_text.rb @@ -2,6 +2,8 @@ require 'cgi' require 'uri' class DText + MENTION_REGEXP = /(?:^| )@\S+/ + def self.u(string) CGI.escape(string) end @@ -36,7 +38,7 @@ class DText str.gsub!(/&/, "&") str.gsub!(/, "<") str.gsub!(/>/, ">") - str.gsub!(/(?:^| )@\S+/) do |name| + str.gsub!(MENTION_REGEXP) do |name| if name =~ /([:;,.!?\)\]<>])$/ name.chop! ch = $1 diff --git a/app/logical/mentionable.rb b/app/logical/mentionable.rb new file mode 100644 index 000000000..ad52df56f --- /dev/null +++ b/app/logical/mentionable.rb @@ -0,0 +1,41 @@ +module Mentionable + extend ActiveSupport::Concern + + module ClassMethods + # options: + # - message_field + # - user_field + def mentionable(options = {}) + @mentionable_options = options + + after_create :queue_mention_messages + end + + def mentionable_option(key) + @mentionable_options[key] + end + end + + def queue_mention_messages + title = self.class.mentionable_option(:title) + from_id = read_attribute(self.class.mentionable_option(:user_field)) + text = read_attribute(self.class.mentionable_option(:message_field)) + + text.scan(DText::MENTION_REGEXP).each do |mention| + mention.gsub!(/(?:^\s*@)|(?:[:;,.!?\)\]<>]$)/, "") + user = User.find_by_name(mention) + body = self.class.mentionable_option(:body).call(self, user.name) + + if user + dmail = Dmail.new( + from_id: from_id, + to_id: user.id, + title: title, + body: body + ) + dmail.owner_id = user.id + dmail.save + end + end + end +end diff --git a/app/models/forum_post.rb b/app/models/forum_post.rb index 8b749e6b8..d7a9f5b44 100644 --- a/app/models/forum_post.rb +++ b/app/models/forum_post.rb @@ -1,4 +1,6 @@ class ForumPost < ActiveRecord::Base + include Mentionable + attr_accessible :body, :topic_id, :as => [:member, :builder, :janitor, :gold, :platinum, :contributor, :admin, :moderator, :default] attr_accessible :is_locked, :is_sticky, :is_deleted, :as => [:admin, :moderator] attr_readonly :topic_id @@ -16,6 +18,12 @@ class ForumPost < ActiveRecord::Base validate :topic_id_not_invalid before_destroy :validate_topic_is_unlocked after_save :delete_topic_if_original_post + mentionable( + :message_field => :body, + :user_field => :creator_id, + :title => "You were mentioned in a forum topic", + :body => lambda {|rec, user_name| "You were mentioned in the forum topic \"#{rec.topic.title}\":#{Danbooru.config.hostname}/forum_topics/#{rec.topic_id}?page=#{rec.forum_topic_page}\n\n