This is a Crystal wrapper for the Elk javascript engine
Elk is a tiny javascript implementation, and the goal of this wrapper is to make it very easy to use and extend from Crystal.
Important: This is not a replacement for duktape or any other JS engine, it's very limited, it has no standard library at all, it doesn't even support arrays, objects or integers!
It's just a simple way to run some JS code in a Crystal runtime that can call back to Crystal code.
On the other hand, if you want to provide some limited scriptability to your Crystal app or library it may be just what you need, and it sure will be easy to use and small.
-
Add the dependency to your
shard.yml
:dependencies: elkjs: github: ralsina/elkjs
-
Run
shards install
The whole API is wrapped in the Elk
module, and a more comfortable
high level API is provided in the Js
module.
Here is an example:
require "elkjs"
# Create a new engine
js = Js::Engine.new
# Define a global function called "print" that will print to stdout
js.set_global("print", Js.func(->(args : Js::Args) {
args.each do |arg|
puts arg
end
Js::UNDEF # Return undefined
}))
# A classic
js.eval("print('Hello, World!');")
# You can loop and define functions
js.eval("
let f = function(i) { return i*2; };
for (let i=0; i<5; i++) {
print(f(i));
}")
# Eval returns the last value
puts js.eval("1+1") # => 2
This doesn't seem to work even tho it's copied from the Elk docs:
js.eval("let obj = {f: function(x) { return x * 2}}; obj.f(3);")
For documentation in the underlying library, see their site and you can always read the source for ElkJS since it's pretty tiny.
- To build the example run
make
- A
src/elk.o
needs to be generated for this to link. I think shard.yml should do that. If not, rungcc -DJS_DUMP -c lib/elkjs/src/elk.c -o lib/elkjs/src/elk.o
- Fork it (https://github.com/ralsina/elkjs/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
- Roberto Alsina - creator and maintainer