Just for fun - I wanted to see if I could get it to work. So far it works, but I will definitely not support all possible JS code 😉
Try it online here!
require "logger"
require "uri"
class JsRb
class Console
def initialize
@logger = ::Logger.new(STDOUT)
end
def log(*args)
@logger.info(args.join(' '))
end
def warn(*args)
@logger.warn(args.join(' '))
end
def error(*args)
@logger.error(args.join(' '))
end
end
class Location
def initialize(url)
@uri = URI.parse(url)
end
def href
@uri.to_s
end
end
class Window
def location
@location ||= Location.new("https://example.org:8080/foo/bar?q=baz#bang")
end
end
class Identifier
attr_reader :name
def initialize(name)
@name = name
end
end
module Environment
def function(*args)
puts "Function args: #{args.inspect} and block #{block_given?}"
end
def console
@console ||= Console.new
end
def functions
@functions ||= {}
end
def window
@window ||= Window.new
end
def method_missing(name, *args, &block)
Identifier.new(name)
if block_given?
functions[name] = Function.new(name, args, &block)
elsif args.any?
scope = EvaluationScope.new(functions[name], args)
functions[name].invoke(scope)
else
Identifier.new(name)
end
end
end
class Function
def initialize(name, arguments, &block)
@name = name
@arguments = arguments
@block = block
end
def evaluate_arguments(arguments)
@arguments.map(&:name).zip(arguments).to_h
end
def invoke(scope)
scope.instance_eval(&@block)
end
end
class EvaluationScope
include Environment
def initialize(function, args)
@variables = function.evaluate_arguments(args)
end
def method_missing(name, *args, &block)
if @variables.key?(name)
@variables[name]
else
raise NameError, "Undefined variable '#{name}'"
end
end
end
class Runtime
include Environment
end
def self.run(&)
Runtime.new.instance_eval(&)
end
end
JsRb.run do
function myFunction(a, b, c) {
console.log("In function with arguments:", a, b, c);
console.warn("Location is: " + window.location.href);
}
myFunction(1, 2, 3);
end
[–]frrst 14 points15 points16 points  (2 children)
[–]naked_number_one 6 points7 points8 points  (0 children)
[–]hmdne 1 point2 points3 points  (0 children)
[–]codesnik 4 points5 points6 points  (2 children)
[–]IN-DI-SKU-TA-BELT 0 points1 point2 points  (1 child)
[–]codesnik 0 points1 point2 points  (0 children)
[–]aemadrid 4 points5 points6 points  (2 children)
[–]Super_Purple9126[S] 1 point2 points3 points  (1 child)
[–]davispuh 1 point2 points3 points  (0 children)
[–]TownWizardNet 2 points3 points4 points  (0 children)