Opalbox—Run Ruby Code Inside Pages
Opal is a Ruby to JavaScript compiler, and OpalBox is a jQuery
plugin to easily create a textarea that can take ruby code and allow it to run.
I just added OpalBox to this blog and it’s been quite interesting. I’ve learned how to resize a textarea
based on its content (you need javascript to do that because CSS
just doesn’t cut it) and I’ve added in a shortcode.
update:
Angelmmiguel (the author of opalbox) has just released 0.1.0 that fixes the issue :)
Here’s how it looks like:
I’ve edited one of my past articles to use OpalBox
if you’re interested in how it looks like as a method for instruction.
Here’s the javascript snippet that resizes the textarea
to fit its content:
var $targets = $(".ruby-code textarea")
$targets.each(function() {
$(this).height(0).height(this.scrollHeight - $(this).css("font-size").replace('px','')).change();
})
The height
is first set to 0
because some browsers get confused with unconventional positions (negative margins, for example). It is then set to the textarea
’s scrollHeight
. I then subtract the font-size
of this element to remove the extra line at the end.
Shortcodes in Hugo (the blog engine this site is running on) is quite simple to make. It’s just a text
snippet that you can call within your article. For example, the above OpalBox
looks like this:
{{< rubycode >}} # this is ruby code # it is inside a text area so you can edit it and play around with it def square(x) x ** 2 end puts square(256) # click on run below to execute the code {{< /rubycode >}}
While the shortcode file contents (rubycode.html
) look like this:
<div class="ruby-code">{{ .Inner }}</div>
I also have the opalbox.html
shortcode that I only include whenever the article contains an OpalBox
. It first runs the .opalBox()
function on all div
that have the class .ruby-code
and turn them into textarea
. Then the textarea
are resized to fit their contents.
$(function() {
$('.ruby-code').opalBox();
var $targets = $(".ruby-code textarea")
$targets.each(function() {
$(this).height(0).height(this.scrollHeight - $(this).css("font-size").replace('px','')).change();
})
});
What I like
- It’s great for tutorial articles that explain complicated concepts.
- The reader can play and manipulate the code to confirm understanding.
What I don’t like
textarea
disables syntax highlighting.- Long ruby code is not practical because it looks like a wall of text.