https://github.com/judofyr/duktape.rb
Ruby bindings to the Duktape JavaScript interpreter
https://github.com/judofyr/duktape.rb
duktape javascript-interpreter
Last synced: 8 months ago
JSON representation
Ruby bindings to the Duktape JavaScript interpreter
- Host: GitHub
- URL: https://github.com/judofyr/duktape.rb
- Owner: judofyr
- Created: 2014-01-11T12:41:43.000Z (almost 12 years ago)
- Default Branch: master
- Last Pushed: 2023-12-01T16:32:24.000Z (almost 2 years ago)
- Last Synced: 2025-03-30T17:11:39.758Z (8 months ago)
- Topics: duktape, javascript-interpreter
- Language: C
- Homepage: http://www.rubydoc.info/gems/duktape
- Size: 3.67 MB
- Stars: 78
- Watchers: 3
- Forks: 7
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
- AwesomeInterpreter - duktape.rb
README
# Duktape.rb
Duktape.rb is a C extension for the [Duktape](http://duktape.org/) JavaScript
interpreter.
## Quickstart
```sh
$ rake
$ ruby example.rb
```
## Usage
```ruby
require 'duktape'
# Create a new context
ctx = Duktape::Context.new
## Evaluate a string
p ctx.eval_string('1 + 1') # => 2.0
```
### Contexts
Creating a context creates a fresh evaluation environment with no global
variables or functions defined.
A common pattern is to create a new context, define static functions once, and
reuse the context to invoke the function many times with `call_prop`.
``` ruby
ctx = Duktape::Context.new
ctx.exec_string <<-JS
function process(str, options) {
// ...
}
JS
ctx.call_prop('process', 'some data', a: 1, b: 2)
```
### Call APIs
* `exec_string` - Evaluate a JavaScript String on the context and return `nil`.
* `eval_string` - Evaluate a JavaScript String expression and return the result
as a Ruby Object.
- `get_prop` - Access the property of the global object and return the value
as a Ruby Object.
- `call_prop` - Call a defined function with the given parameters and return
the value as a Ruby Object.
### Defining functions
You can define simple functions in Ruby that can be called from
JavaScript:
```ruby
ctx.define_function("leftpad") do |str, n, ch=' '|
str.rjust(n, ch)
end
```
### Exceptions
Executing JS may raise two classes of errors: `Duktape::Error` and
`Duktape::InternalError`.
Any JS runtime error that is thrown in the interpreter is converted to a Ruby
`Duktape::Error`. Specific error subclasses, such as `SyntaxError` and
`TypeError`, are mapped from JS to the Ruby equivalent of the same name.
``` ruby
ctx = Duktape::Context.new
ctx.exec_string <