Opalbox—Run Ruby Code Inside Pages

Opal is a Ruby-to-JavaScript compiler, and OpalBox is a jQuery plugin for easily creating a textarea where you can enter and run Ruby code.

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 a shortcode.

Update:

Angelmmiguel (the author of OpalBox) has just released 0.1.0, which fixes the issue :)

Here’s what it looks like:

# 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

I’ve edited one of my past articles to use OpalBox if you’re interested in seeing how it works as an instructional method.

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 element’s font-size to remove the extra line at the end.

Shortcodes in Hugo (the blog engine this site is running on) are quite simple to make. A shortcode is 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 >}}

The shortcode file (rubycode.html) looks like this:

<div class="ruby-code">{{ .Inner }}</div>

I also have the opalbox.html shortcode, which I include whenever the article contains an OpalBox. It first runs the .opalBox() function on all div elements with the class .ruby-code and turns them into textarea elements. Then the textarea elements 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

What I don’t like

Comments

comments powered by Disqus