Documentation ¶
Overview ¶
Package mruby embeds the Ruby programming language into your Go project. mruby is a lightweight implementation of the Ruby language complying to the ISO standard. mruby can be linked and embedded within an application. This package makes mruby available in your Go projects, effectively enabling Ruby as a scripting language within your Go code.
mruby went 1.0.0 on 9th Feb 2014. The current version of mruby is 1.1.0, and mruby-go is tested with it.
You can find the mruby source code at https://github.com/mruby/mruby. Tarballs are available from https://github.com/mruby/mruby/releases.
Example:
ctx := mruby.NewContext() ctx.LoadString("p 'Hello world'")
If successful, these two lines of code will print "Hello world!" to stdout.
Example ¶
// Create a new context ctx := mruby.NewContext() // Run a script that returns the value of 1+2 val, err := ctx.LoadString("1 + 2") if err != nil { fmt.Println("LoadStringResult failed") return } // Convert the value to an int i, err := val.ToInt() if err != nil { fmt.Println("Result is not a Fixnum") return } fmt.Printf("1+2=%d\n", i)
Output: 1+2=3
Example (AutomaticallyConvertToGoInterface) ¶
// Create a new context ctx := mruby.NewContext() // Run a script that returns the value of 1+2 and directly converts to Go res, err := ctx.LoadStringResult("1 + 2") if err != nil { fmt.Println("LoadStringResult failed") return } fmt.Printf("1+2=%d", res)
Output: 1+2=3
Example (WithArguments) ¶
// Create a new context. ctx := mruby.NewContext() // Run a script that adds all values and directly converts the result to Go. // The args of LoadStringXXX will be available via ARGV in the script. res, err := ctx.LoadStringResult("ARGV.inject { |x,y| x+y }", 1, 2, 3.5) if err != nil { fmt.Println("LoadStringResult failed") return } fmt.Println(res)
Output: 6.5
Index ¶
- Variables
- func SetFilename(filename string) func(*Context)
- func SetNoExec(noExec bool) func(*Context)
- type Args
- type Class
- type Context
- func (ctx *Context) DefineClass(name string, super *Class) (*Class, error)
- func (ctx *Context) DefineClassUnder(name string, super *Class, outer RClass) (*Class, error)
- func (ctx *Context) DefineModule(name string, outer RClass) (*Module, error)
- func (ctx *Context) GC()
- func (ctx *Context) GetArgs() ([]Value, error)
- func (ctx *Context) GetClass(name string, outer RClass) (*Class, bool)
- func (ctx *Context) GetModule(name string, outer RClass) (*Module, bool)
- func (ctx *Context) HasClass(name string, outer RClass) bool
- func (ctx *Context) HasModule(name string, outer RClass) bool
- func (ctx *Context) IncrementalGC()
- func (ctx *Context) KernelModule() *Module
- func (ctx *Context) LoadString(code string, args ...interface{}) (Value, error)
- func (ctx *Context) LoadStringResult(code string, args ...interface{}) (interface{}, error)
- func (ctx *Context) ObjectClass() *Class
- func (ctx *Context) ObjectModule() *Module
- func (ctx *Context) Parse(code string) (*Parser, error)
- func (ctx *Context) ToValue(value interface{}) (Value, error)
- type Function
- type Module
- type ParseError
- type Parser
- type RClass
- type RunError
- type Value
- func (v Value) IsArray() bool
- func (v Value) IsBool() bool
- func (v Value) IsFixnum() bool
- func (v Value) IsFloat() bool
- func (v Value) IsHash() bool
- func (v Value) IsNil() bool
- func (v Value) IsProc() bool
- func (v Value) IsString() bool
- func (v Value) IsSymbol() bool
- func (v Value) Run() (Value, error)
- func (v Value) String() string
- func (v Value) ToArray() ([]interface{}, error)
- func (v Value) ToBool() (bool, error)
- func (v Value) ToFloat32() (float32, error)
- func (v Value) ToFloat64() (float64, error)
- func (v Value) ToInt() (int, error)
- func (v Value) ToInt16() (int16, error)
- func (v Value) ToInt32() (int32, error)
- func (v Value) ToInt64() (int64, error)
- func (v Value) ToInt8() (int8, error)
- func (v Value) ToInterface() (interface{}, error)
- func (v Value) ToMap() (map[string]interface{}, error)
- func (v Value) ToString() (string, error)
- func (v Value) ToUint() (uint, error)
- func (v Value) ToUint16() (uint16, error)
- func (v Value) ToUint32() (uint32, error)
- func (v Value) ToUint64() (uint64, error)
- func (v Value) ToUint8() (uint8, error)
- func (v Value) Type() ValueType
- type ValueType
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidType is returned when the package cannot convert a Ruby // type to the Go equivalent. ErrInvalidType = errors.New("invalid type") )
Functions ¶
func SetFilename ¶
SetFilename sets the filename to be used in the context (default: "(mruby-go)"). It is used for configuring a Context (see NewContext for details).
Types ¶
type Args ¶
Args is used to specify the number of arguments a Go extension method will use. Use one of the ArgsAny, ArgsNone, ArgsRequired, ArgsOptional, or ArgsArg helper functions to initialize it.
func ArgsOptional ¶
ArgsOptional specifies a function that accepts a number of options arguments.
func ArgsRequired ¶
ArgsRequired specifies a function that accepts a number of required arguments.
type Class ¶
type Class struct {
// contains filtered or unexported fields
}
Class represents a class in Ruby.
func NewClass ¶
NewClass defines a new class with the given name and super-class in the context. If super is nil, ObjectClass is used by default.
func NewClassUnder ¶
func (*Class) DefineClassMethod ¶
DefineMethod registers a class method with the name in the class. The function is called when executed in Ruby.
func (*Class) DefineMethod ¶
DefineMethod registers an instance method with the name in the class. The function is called when executed in Ruby.
func (*Class) RClass ¶
func (c *Class) RClass() *C.struct_RClass
RClass returns the MRuby object of type *struct RClass.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context serves as the entry point for all communication with mruby.
func NewContext ¶
NewContext creates a new mruby context. Use the options to handle configuration.
Examples:
ctx := mruby.NewContext() ctx := mruby.NewContext(mruby.SetNoExec(true), mruby.SetFilename("simple.rb"))
func (*Context) DefineClass ¶
DefineClass defines a new class with the given name and super-class in the context. If super is nil, ObjectClass is used by default.
func (*Context) DefineClassUnder ¶
DefineClassUnder defines a new class with the given name and super-class under e.g. a specific module in the context. If super is nil, ObjectClass is used by default. If under is nil, the top-level module is used.
func (*Context) DefineModule ¶
DefineModule defines a new module with the given name under outer. If outer is nil, the registered module is a top-level module.
func (*Context) IncrementalGC ¶
func (ctx *Context) IncrementalGC()
GC runs the incremental MRuby garbage collector.
func (*Context) KernelModule ¶
KernelModule runs the class for the Kernel module.
func (*Context) LoadString ¶
LoadString loads a snippet of Ruby code and returns its output. An error is returned if the interpreter failes or the Ruby code raises an exception of type RunError.
func (*Context) LoadStringResult ¶
LoadStringResult invokes LoadString and returns the Go value immediately. Use this method to skip testing the returned Value.
func (*Context) ObjectClass ¶
ObjectClass runs the class for Object class.
func (*Context) ObjectModule ¶
ObjectModule is the same as ObjectClass, however it returns a Module.
type Function ¶
Function defines the signature of a Go function that can be called from within a MRuby script.
Example ¶
// Create a new context, and set some options ctx := mruby.NewContext() if ctx == nil { fmt.Println("Cannot initialize context") return } // sayHello is an extension method that can be called from Ruby. sayHello := func(ctx *mruby.Context) (output mruby.Value, err error) { // We expect a string here. args, err := ctx.GetArgs() if err != nil { return mruby.NilValue(ctx), err } if len(args) == 1 { s, err := args[0].ToString() if err != nil { return mruby.NilValue(ctx), err } s = fmt.Sprintf("Hello %s!", s) return ctx.ToValue(s) } return mruby.NilValue(ctx), nil } // We create a new module called Helpers that will hold our extension method. module, err := ctx.DefineModule("Helpers", nil) if err != nil { fmt.Println("Cannot create module") return } if module == nil { fmt.Println("Method is nil") return } // Now we register the extension method. It will be available as // Helper.say_hello from within Ruby and requires 1 argument. module.DefineClassMethod("say_hello", sayHello) greeting, err := ctx.LoadStringResult("Helpers.say_hello(ARGV[0])", "Matz") if err != nil { fmt.Printf("Cannot execute say_hello method: %v\n", err) return } fmt.Println(greeting)
Output: Hello Matz!
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module is a Ruby module.
func NewModule ¶
NewModule defines a new module with the given name under outer. If outer is nil, the registered module is a top-level module.
func (*Module) DefineClassMethod ¶
DefineClassMethod registers a class method with the name in the module. The function is called when executed in Ruby.
func (*Module) DefineMethod ¶
DefineMethod registers a method with the name in the module. The function is called when executed in Ruby.
func (*Module) RClass ¶
func (m *Module) RClass() *C.struct_RClass
RClass returns the MRuby object of type *struct RClass.
type ParseError ¶
ParseError is used to indicate errors while parsing Ruby code.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser is a parser for Ruby code. It can be used to parse Ruby code once and run it multiple times.
Example ¶
// Create a new context ctx := mruby.NewContext() // Create a parser to parse the given code code := ` def concat(a, b) a + b end concat "Hello", "World" ` parser, err := ctx.Parse(code) if err != nil { fmt.Println("Parser cannot parse") return } // Run the code val, err := parser.Run() if err != nil { fmt.Println("Run failed") return } res, err := val.ToInterface() if err != nil { fmt.Println("Cannot convert") return } s, ok := res.(string) if !ok { fmt.Println("Not a string") return } fmt.Println(s)
Output: HelloWorld
type RClass ¶
type RClass interface {
RClass() *C.struct_RClass
}
type RunError ¶
type RunError struct {
Message string // Message details
}
RunError is used to indicate errors while running Ruby code.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is used for encoding/decoding data types from MRuby to Go and vice versa.
func (Value) IsBool ¶
IsBool indicates whether this value is a bool.
Notice: In Ruby, everything that is not false is a boolean. However, this method respects the Go type bool that has two distinct values: true or false.
func (Value) IsFixnum ¶
IsFixnum indicates whether this value is a fixed number.
Notice: Ruby only has fixed numbers and floats. So there is no equivalent to e.g. int8 or uint16.
func (Value) IsFloat ¶
IsFloat indicates whether this value is a float.
Notice: Ruby only has fixed numbers and floats. So this method returns true if the Ruby type is a float and therefore can be converted to float32.
func (Value) ToArray ¶
ToArray treats this value as an array and returns its values. If the value is not a Ruby Array, an error is returned.
func (Value) ToBool ¶
ToBool treats this value as a bool and returns its value. If the value is not a bool, an error is returned.
func (Value) ToFloat32 ¶
ToFloat32 treats this value as a float32 and returns its value. If the value is not a Ruby Float, an error is returned.
func (Value) ToFloat64 ¶
ToFloat64 treats this value as a float64 and returns its value. If the value is not a Ruby Float, an error is returned.
func (Value) ToInt ¶
ToInt treats this value as an int and returns its value. If the value is not a Ruby Fixnum, an error is returned.
func (Value) ToInt16 ¶
ToInt16 treats this value as an int16 and returns its value. If the value is not a Ruby Fixnum, an error is returned.
func (Value) ToInt32 ¶
ToInt32 treats this value as an int32 and returns its value. If the value is not a Ruby Fixnum, an error is returned.
func (Value) ToInt64 ¶
ToInt64 treats this value as an int64 and returns its value. If the value is not a Ruby Fixnum, an error is returned.
func (Value) ToInt8 ¶
ToInt8 treats this value as an int8 and returns its value. If the value is not a Ruby Fixnum, an error is returned.
func (Value) ToInterface ¶
ToInterface will return the Go-equivalent of the Ruby value. It will only handle the following Ruby types: TrueClass, FalseClass, NilClass, Fixnum, Float, Symbol, String, Array, and Hash. All other Ruby types return nil.
func (Value) ToMap ¶
ToMap treats this value as a hash and returns its values as a map. If the value is not a Ruby Hash, an error is returned.
func (Value) ToString ¶
ToString returns a string for MRuby types String and Symbol. If the value is not a Ruby String or Symbol, an error is returned.
func (Value) ToUint ¶
ToUint treats this value as an uint and returns its value. If the value is not a Ruby Fixnum, an error is returned.
func (Value) ToUint16 ¶
ToUint16 treats this value as an uint16 and returns its value. If the value is not a Ruby Fixnum, an error is returned.
func (Value) ToUint32 ¶
ToUint32 treats this value as an uint32 and returns its value. If the value is not a Ruby Fixnum, an error is returned.
func (Value) ToUint64 ¶
ToUint64 treats this value as an uint64 and returns its value. If the value is not a Ruby Fixnum, an error is returned.