How I implemented a “Raw” code link in Markdown with Redis
For Forrst v3, one of the more annoying things about the Markdown formatting available in post descriptions and comments is that, unlike code posts themselves, other user-added code blocks don’t have the same “Raw” link, making it somewhat annoying to copy and paste code. For reference:
Here’s a code block as part of an actual code post: http://cl.ly/0l1c1f1J3p0C471z2233 And here’s a code block in a comment: http://cl.ly/1Q3l3U012h2g1g0u2y1N
Additionally, I’d love to integrate something like JSFiddle, do give users a chance to one-click get a sandbox with which to experiment with html/css/js code.
I just whipped up what I think is a somewhat interesting solution to the problem. In the PHP Markdown library, within _doCodeBlocks_callback, I added the following code:
$redis = Magnus::get_redis();
$fp = sha1(Magnus::$config['security.key'] . $codeblock);
$redis->setnx("timber:raw.code:{$fp}", $codeblock);
unset($redis);
This way, every single code block that markdown parses is fingerprinted using sha1 and pushed into Redis. The code block is then returned to the Markdown parser with an additional bit of html: a hyperlink to something like “/raw_code/$fp”. The posts controller in Forrst attempts to get data using that fingerprint from Redis, and if found, serves a basic text/plain response with the raw code. In the future, I hope to use a similar method to allow one-click JSFiddle creation (maybe even Pastie, Gist, etc., too).
Perhaps a simple solution, but I’m quite happy with the result thus far, and look forward to pushing this live in a few weeks.