Extending RedCloth
Posted by hardwarehank, Wed Sep 13 14:52:31 UTC 2006
I wanted to put emoticons into Textile for Beast, but to do it, I needed to use very few lines of code since there is a 500LOC limit on Beast. After a long time debugging, here’s what I came up with:
First, I made a new method in the RedCloth namespace.
class RedCloth
def refs_smiley(text)
text.gsub!(/(\s)~(:P|:D|:O|:o|:S|:\||;\)|:'\(|:\)|:\()/) do |m|
bef,ma = $~[1..2]
filename = ActionController::AbstractRequest.relative_url_root+"/images/emoticons/"+(ma.split(//).collect{|l|l[0]}.join('_'))+".png"
"#{bef}<img src='#{filename}' title='#{ma}' class='smiley' />"
end
end
end
All I’m doing here is some nifty gsubbing with a block. The resultant replacement expression is the last thing returned by the block. This RegExp will match any of the possible emoticons I specified as long as they are preceeded by a ~. This prevents things like :Person from being converted into :Person. Here is the post about it with all the emotes I allow. Try it out. While I was at it, I re-activated tables for Textile in Beast. This was totally necessary. ;)
Then I changed the text format helper in Beast to reflect my new method:
def format_text(text)
RedCloth.new(auto_link(text.to_s)).to_html(:textile,:refs_smiley)
end
The key part here is the options passed to to_html. This allows you to pick any rules you want for your code generation. I found that when I named the method smiley, it wouldn’t be called. That’s because there is a RegExp match that happens when the rule methods are called that matches on methods that begin with refs_. I think you could get around that somehow, but I just went with it. The default options that are implicit on a call of to_html are :markdown,:textile, and as you can see, I left out markdown. Also, I realized that white_list was causing my generated tables to be ruined, so I took that out. This might be a little dangerous, but I’m not too worried at this point. I might have to submit a patch (or make a modification) to the white_list plugin. The possibilities here are endless, thanks to _why.

Blog Posts
September 14, 2006 @ 06:05 AM
September 14, 2006 @ 06:10 AM
September 14, 2006 @ 09:18 AM
September 15, 2006 @ 07:17 AM
September 17, 2006 @ 03:46 PM