Goè¨èªä¾¿å©ã ãã©ãææ³ãããããåãã¦å é¨DSLãä½ãã¨ãã«ã¯åãã¦ããªãã®ã§ãã«ãã¼é¢¨ã«DSLãèªã¿è¾¼ã¾ãã¦è¨å®ã¨æ¿ãããã¦ããã ãã¾ããã¨è¨ãã®ãå°ãé£ããã
ãã£ãGoå é¨ã§Rubyãçµã¿è¾¼ãã§å®è¡ããããmrubyãªãã§ããããããï¼ãã¨æã£ã¦ãã£ã¦ã¿ããããã£ã½ãã®ãã§ããã
VagrantãPackerãConsulãªã©ãDevOps対å¿çéã§ãã®åãç¥ããªãè ã¯ããªã mitchellh ããã®
ãã¤ããã
å¤åã ãã©ããã·ã¢ãæ°ãåããããªãã¨èãã¦ãããããªãã ããããçµå±
hashicorp/hcl · GitHub ã使ããã¦ãããã©ã
å®æããããã£ã½ãã®.go
package main import ( "fmt" "io/ioutil" "os" "github.com/mitchellh/go-mruby" ) func main() { mrb := mruby.NewMrb() defer mrb.Close() file, err := os.Open("./Samplefile") if err != nil { panic(err) } defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { panic(err) } src := string(data[:]) fmt.Printf("src is:\n%v\n", src) inFoobar := false parsedConfig := make(map[string]string) mrb_foobarBlock := func(m *mruby.Mrb, self *mruby.MrbValue) (mruby.Value, mruby.Value) { inFoobar = true args := m.GetArgs() _, err := m.Yield(args[0]) if err != nil { panic(err.Error()) } inFoobar = false return mruby.Nil, nil } mrb_buz := func(m *mruby.Mrb, self *mruby.MrbValue) (mruby.Value, mruby.Value) { if !inFoobar { return mruby.Nil, nil } args := m.GetArgs() parsedConfig["buz"] = args[0].String() return m.TrueValue(), nil } mrb_fizz := func(m *mruby.Mrb, self *mruby.MrbValue) (mruby.Value, mruby.Value) { if !inFoobar { return mruby.Nil, nil } args := m.GetArgs() parsedConfig["fizz"] = args[0].String() return m.TrueValue(), nil } kernel := mrb.KernelModule() kernel.DefineMethod("foobar_block", mrb_foobarBlock, mruby.ArgsBlock()) kernel.DefineMethod("buz", mrb_buz, mruby.ArgsReq(1)) kernel.DefineMethod("fizz", mrb_fizz, mruby.ArgsReq(1)) _, err = mrb.LoadString(src) if err != nil { panic(err.Error()) } fmt.Printf("parsed data is:\n%v\n", parsedConfig) }
Goãåå¿è ãªã®ã§ãã³ã¼ããã²ã©ãã®ã¯åå¼ã
mruby - GoDoc ãçºãã¦ä½ã¨ãªãæ¸ããã大ä¸å¤«ã ã£ãããããã¯ã使ããããã¶ããCã§mrubyåãã®ã³ã¼ããæ¸ããçµé¨ããã人ãªããã£ã¨ã¹ã ã¼ãºã«æ¸ãããã
foobar_block do buz "hogehoge" fizz "fugafuga" end buz "waiwai" fizz "wakuwaku"
ã¿ãããªRubyã®DSLãåããã£ã¬ã¯ããªã«ç½®ãã¨ãã¦å®è¡ããã
$ go run sample.go src is: foobar_block do buz "hogehoge" fizz "fugafuga" end buz "waiwai" fizz "wakuwaku" parsed data is: map[buz:hogehoge fizz:fugafuga]
buz/fizz ã¡ã½ããããã¡ããã¨ãããã¯ã®ä¸ã§å®è¡ãããã¨ãã®ã¿æå¹ã«ãªã£ã¦ãããã§ãmrubyå´ã®ã¡ã½ããå®è¡çµæãGoã§ã®mapã«å¯¾å¿ãã¦ããã
Tips
ãã«ãããã³ãããã£ã¦ã go run/build ãå®è¡ãããã£ã¬ã¯ããªã¨åãæã« libmruby.a ãç½®ãã¨ããªãã¨ã³ã³ãã¤ã«ã§ããªãã£ããéã«ã好ããªmrbgemãçµã¿è¾¼ãã libmruby.a ãç¨æãã¦å©ç¨ãããã¨ãã§ããã¿ããã
ãã¼ã¿ããªãã£çã«ã¯ãã«ãå¾ã®ãã¤ããªã« libmruby.a ã丸ã£ã¨çµã¿è¾¼ã¾ããã¿ãããªã®ã§ãã«ããã¦ã³ãã¼ããã°ä½¿ããããéã«ã¯ãã¹ã³ã³ãã¤ã«ã¨ã... ã©ããããã ããã
ãã¨ãDSLã®ã¨ããå ¨ç¶ä¸¦è¡æ§ã¨ãèãã¦ããªããã©ããã£ã³ãã«ã¨ãæ¬æ°ã§ä½¿ãã°ãã¾ãããããããããªãã
ã½ã¼ã¹ã§ããã GitHub ã«ãç½®ãã¨ããã®ã§ããã£ã¦ã¿ã¦ãã ãããmakeä¸çºã§åãã¾ã â
udzura/dsl-with-go-mruby · GitHub