To use Ruby as a scripting language, that is, as an embedding language like lua, there is a lightweight Ruby implementation called MRuby .
Only one stable mruby-bound library has been found for go . By default, it can build mruby version 1.2.0 (2015 release), and you can try to build up to version 1.4.1 (2018 release). But the current version of mruby now has version 2.1.2 (2020). There is a fork with support for mruby 2.1.0 . We will use this fork to get version 2.1.2 after some minor changes.
In versions older than 2.1.0, they introduced at least the following incompatibilities that should be noted.
Version 2.1.1 :
Remove MRB_INT16 configuration option.
Version 2.1.2
IO#readchar returns a UTF-8 character fragment instead of EOFError if EOF is reached in the middle of UTF-8 characters. (86271572) This behavior is different from CRuby, but it is a mruby specification that supports either ASCII or UTF-8 exclusively.
Remove mrb_run() from C APIs.
go-mruby mrb_run. "Breaking Changes" . go-mruby:
https://github.com/mrbgems/go-mruby/tree/mruby-2 mruby-2.
go.mod go.sum go-mruby. , go . , go , go . go-mruby vendor .
mruby.go Run(), RunWithContext().
Makefile MRUBY_COMMIT 2.1.2 - mruby.
make. mruby vendor libmruby.a.
. mruby-error (https://github.com/mitchellh/go-mruby/pull/75). mruby require . . http://mruby.org/libraries/, mruby/build_config.rb . mruby/examples/mrbgems , mruby/mrbgems . , mruby-metaprog.
Let's try to enable json support. To do this, you need to register the library in go-mruby / build_config.rb:
gem :github => 'iij/mruby-iijson'
An example of using JSON.parse, while, as you can see, the symbolize_names option is apparently not supported by this library.
func main() {
mrb := mruby.NewMrb()
defer mrb.Close()
class := mrb.DefineClass("Example", nil)
class.DefineClassMethod("json_value", func(m *mruby.Mrb, self *mruby.MrbValue) (mruby.Value, mruby.Value) {
return mruby.String(`{"int":1, "array":["s1", "s2", {"nil": null}]}`), nil
}, mruby.ArgsReq(1))
result, err := mrb.LoadString(`JSON.parse(Example.json_value, {"symbolize_names" => true})`)
if err != nil {
panic(err.Error())
}
// Result: {"int"=>1, "array"=>["s1", "s2", {"nil"=>nil}]}
fmt.Printf("Result: %s\n", result.String())
}