Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you've described is the basic way; anything else is not terribly more elegant. It's helpful to see it as two parts: one is on receipt of the comment (when you should do notifications) and the other is on display of the comment, when you should do linkification.</p> <p>This allows you to keep the original comment in its original form, which is helpful.</p> <p>Perhaps put an after_create (so notifications aren't sent on every edit) on the comment model (assuming a comment model that includes a 'body' field):</p> <p><em>[edit: added contextual info]</em></p> <pre class="lang-ruby prettyprint-override"><code>after_create :notify_mentions def notify_mentions body.scan %r{(.{0,40})@(\w+)(.{0,20})} do |match| username = match[1] context = [match.first, match.last] Notification.send(match, context, self) if User.exists?(:login =&gt; username) end end </code></pre> <p>I use <code>\w+</code> in place of <code>\S+</code> because people often say things like:</p> <blockquote> <p>Hey @JohnMetta, how are you doing?</p> </blockquote> <p>and <code>\S+</code> will capture the <code>,</code> which might be wrong. Pulling the <code>@</code> out of the capture group lets me ignore it during notification.</p> <p>The <code>context</code> in the above match groups consists of the 40 characters before and 20 characters after the matched username for your snippet. Adjust to taste.</p> <p>Then when displaying the message, you essentially create a helper something like what you had:</p> <pre class="lang-ruby prettyprint-override"><code>def linkify(body) body.gsub %r{@\w+} do |match| link_to match, :controller =&gt; :users, :action =&gt; :show, :id =&gt; match end end </code></pre> <p><code>#gsub</code> is awesome like that, in that it takes a block and replaces with the contents.</p> <p>It's not a lot more elegant than what you had, but it should give a pretty decent result.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload