3 Tricks to debug Opal code from your browser

1. Use pp

pp stands for Pretty Print and is part of the CRuby standard library. Usually what it does is just reformatting your output to make it readable.

require 'pp'
pp 10.times.map { 'hello' }

In CRuby would output:

["hello",
 "hello",
 "hello",
 "hello",
 "hello",
 "hello",
 "hello",
 "hello",
 "hello",
 "hello"]

Opal instead will just pass the object to console.log():

console.log output in Safari's console

2. Call Ruby methods from the browser console

Another good thing to keep in mind is how methods are mapped into JavaScript, the rule is really simple: $ is prefixed to the method name.

> Opal.top.$puts('hello world');
=> "hello world"

> Opal.Object.$new().$object_id();
=> 123

Once you know that, you can also learn how to call methods with and without blocks:

> Opal.send(Opal.top, 'puts', 'hello world');
=> "hello world"

> var object = Opal.send(Object, 'new');
> Opal.send(object, 'object_id');
=> 123

> Opal.block_send([1,2,3], 'map', function(n) { return n*2 });
=> [2,4,6]

> Opal.block_send([1,2,3], 'map', function(n) { return Opal.send(n, '*', 2); });
=> [2,4,6]

3. Inspecting instance variables

Last but not least remember that instance variables are mapped to simple unprefixed properties of the JavaScript object.

Opal code:

class Person
  def initialize(name)
    @name = name
  end
end

In the console (with JavaScript):

> var person = Opal.Person.$new('Pippo');
=> #<Person:123 @name="Pippo">

> person.name
=> "Pippo"

Conclusion

That’s all for now, happy hacking!