Monday, June 11, 2012

Posting code on your blog

If I want to have a technical blog, I better figure out an easy way to post code.  I looked around and found what appears to be the golden goose: quick, easy, very pretty.



Check out gist - a simple tool, which enables you to create your code snippet on github, embed it using something as simple as:

<script src="https://gist.github.com/2914590.js"></script>

and post looking as pretty as this:



There is one caveat: your RSS readers do not get to process javascript! Though that is horribly sad, you do need to account for the readers and display the standard ugliness:

<noscript><pre>
code here
</pre></noscript>

This is what the beautiful snippet above will look like:

function Track(src, spriteLength) {
  var audio = document.createElement('audio');

  audio.src = src;
  audio.autobuffer = true;
  audio.load(); // force the audio to start loading...doesn't work in iOS

  this.audio = audio;
  this.spriteLength = spriteLength;
}

Track.prototype.play = function (position) {
  var track = this,
      audio = this.audio, // the audio element with our sprite loaded
      length = this.spriteLength, // the length of the individual audio clip
      time = position * length,
      nextTime = time + length;

  audio.pause();
  audio.currentTime = time;
  audio.play();

  // clear any stop monitoring that was in place already
  clearInterval(track.timer);
  track.timer = setInterval(function () {
    if (audio.currentTime &amp;amp;gt;= nextTime) {
      audio.pause();
      clearInterval(track.timer);
    }
  }, 10);
};
Not great, but better than nothing.  :-)  Note that you will need to paste the code while in Compose mode, so it would properly escape all html brackets.  To simplify the process I would do something like this:


  • Add temporary markers first:
    START
    END
  • Paste code in-between
    START
    my $var = 'hello';
    END
  • Switch to HTML mode
  • Add script tags above START :
    <script src="..."></script>
    START
    my $var = 'hello';
    END
  • Add noscript tags, replacing START and END
    <script src="..."></script>
    <noscript><pre>
    my $var = 'hello';
    </pre></noscript>
  • All done!

From now on, only pretty code snippets in this blog. Enjoy!


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Powerade Coupons