Smilies in Rails using RedCloth

There’s also a guide to use Smilies in Rails using BBCodeizer.

RedCloth doesn’t come with support for smilies, so i’ve added it for one of my projects.
You need to extend the RedCloth class. You could do this by creating a file in your /lib directory, which you have to include in your environment.rb. Here an example for three simple smilies:

class RedCloth
  def glyphs_smilies(text)
    text.gsub!(/\:\-?\)/, '<img src="/images/emoticons/smile.png" alt="smile" />')
    text.gsub!(/\;\-?\)/, '<img src="/images/emoticons/wink.png" alt="wink" />')
    text.gsub!(/\:\-?\(/, '<img src="/images/emoticons/sad.png" alt="sad" />')
  end
end

To include this new function in your views, write an helper, e.g. format_text in ApplicationHelper:

module ApplicationHelper
  def format_text(text)
    RedCloth.new(text).to_html(:textile, :glyphs_smilies)
  end
end

Now you could use it anywhere in your views, like

  <%= format_text ":)" %>

or

  <%= format_text @your_record.your_text %>

Of course, you have to put some smilies in /images/emoticons :)

Keywords: smiley, smileys, smilie, smilies, rails, textile, redcloth, ruby, emoticon, emoticons

3 Responses to “Smilies in Rails using RedCloth”

  1. Hi,

    Your regular expressions need not be so long:

    [code]/\:\-?\)/[/code]

    would suffice.

  2. thanks!

  3. [...] already described how to enable support for Smilies in Rails using RedCloth. If you want to use BBCodeizer instead of RedCloth (Textile), here’s how to do [...]

Leave a Reply


linkboost