Search code examples
rubyopalrb

Opal.rb anonymous function in native object


Is it possible to somehow achieve methods/lambda assigned in Hash to compile to native functions in native object? for example let

x = {foo: "foo", bar: ->{"bar"}}

I need that x to be compiled like such native object:
pseudo

x.to_n 
=>
Object {foo: 'bar', bar: function(){return "bar";}}

OK THAT WORKS AS EXPECTED ALMOST

is there a way to transpile method to native function e.g.

def foo
 'bar'
end

apply something like

(??:foo??).to_n
=>
function(){return "bar";};

?


Solution

  • I'm guessing you want to pass a ruby method as a callback to a javascript function, you could try something like this:

       x = { bar: method(:foo).to_proc }
       x.to_n
    

    But bear in mind that this might not work as intended for class methods ( the context might change on javascript)

    Another option is just wrap that method call on a lambda

       x = { bar: ->{ foo } }
       x.to_n
    

    This seems a safer approach on my experience


    EDIT:

    My first answer just referenced method(:foo), but when you call this you get a Method object which opal doesn't bridge properly to an anonymous function, so it would require you to use it like this on javascript:

      console.log(#{x.to_n}.bar.$call())
    

    To have it work as a function you need it to be a proc, so the need to call to_proc, and again this will probably broke if its a instance method

      class Test
        def initialize
          @var = "baz"
        end
        def foo
          "bar #{@var}"
        end
      end
    
      t = Test.new
      x = { bar: t.method(:foo).to_proc }
      `console.log(#{x.to_n}.bar())` # bar undefined
      y = { bar: ->{ t.foo } }
      `console.log(#{y.to_n}.bar())` # bar baz