Rubyã¨namespaceã¨æ¡å¼µã©ã¤ãã©ãªã«ã¤ãã¦
2020年代ã¯ã¢ããªã¹ã®æ代
ãã10å¹´ã»ã©æµè¡ã£ã¦ãããã¤ã¯ããµã¼ãã¹ã«ã¤ãã¦ã®ç解ãæ·±ã¾ãããã®éçãåºãç¥ãããããã«ãªã£ã¦ãããShopifyã®Modular Monolithã«ã¤ãã¦ã®è¨äºãªã©ã¯ä»£è¡¨ä¾ã ããã並è¡ãã¦å¿ è¦æ§ãå«ã°ããããã«ãªã£ã¦ããã®ãnamespaceã ãRubyKaigi 2023ã§ã¯shioyamaãããMultiverse Rubyã¨é¡ãã¦çºè¡¨ããã¦ãããããã®å¾tagomorisãããè¨äºãæ¸ãã¦ãã
Rubyã§ã¯ä»¥åããnamespaceã¸ã®è°è«ãè¡ããã¦ã¯ããã®ã ããRuby 2.0ã®é ã®è°è«ã§ã¯ä¸»ã«Monkey Patchingã«ããå¯ä½ç¨ãå±æåããããã®ãã®ã ã£ããå½æã®è°è«ã¨ã¯ã©ã¤ãã©ãªèªã¿è¾¼ã¿ã®å±æåã¨ãã課é¡ãæãã£ã¦ããç¹ãç°ãªã£ã¦ãããããã«ä¼´ãæè¡çãªå°é£ãç°ãªããä¸è¿°ã®è¨äºã§ããããã®å¤ãã¯æ´çããã¦ããã®ã ãããã®è¨äºã§ã¯ã¾ã è°è«ã®æ·±ã¾ã£ã¦ããªãç¹ã«ã¤ãã¦èãã¦ã¿ãã
æ¡å¼µã©ã¤ãã©ãª
Rubyã«namespaceãå°å ¥ããã«å½ãã£ã¦èª²é¡ã¨ãªãã®ããæ¡å¼µã©ã¤ãã©ãªã ãä½ãåé¡ãªã®ããç解ããã«ã¯ãã¾ããæ¡å¼µã©ã¤ãã©ãªãã¨ã¯ä¸ä½ä½ãªã®ããæ¹ãã¦èããå¿ è¦ãããã
æ¡å¼µã©ã¤ãã©ãªã¯ã¤ã¾ãã¨ãããDLLï¼Dynamically Link Libraryãåçãªã³ã¯ã©ã¤ãã©ãªãå
±æã©ã¤ãã©ãªã¨ãè¨ãï¼ã§ãããRubyã®æ¡å¼µã©ã¤ãã©ãªã¯ Init_{ã©ã¤ãã©ãªå}
ï¼foo.so
ãªãã° Init_foo
ã¨ããååï¼ã¨ããé¢æ°ãæã£ã¦ããããã®é¢æ°ã§ã¯ã©ã¹ãã¢ã¸ã¥ã¼ã«ãã¡ã½ãããªã©ãå®ç¾©ãããRuby㧠require "foo.so"
ãªã©ã¨ããå ´åãRuby㯠dlopen(3) ãç¨ãã¦ãã®DLLãéãã Init_foo
ãå¼ã¶ãã¨ã§ã¯ã©ã¹ãã¡ã½ãããªã©ãå®éã«å®ç¾©ãããã
åã ã§çºçããåé¡ã¯ä¸»ã«ä»¥ä¸ã®ä¸ã¤ã¨ãªã * Rubyã§ãã®ã©ã¤ãã©ãªã使ãéã®ã¯ã©ã¹åã»ã¢ã¸ã¥ã¼ã«å * ãã®ã©ã¤ãã©ãªãä¾åå ã©ã¤ãã©ãªã®ã·ã³ãã«åã®è¡çª * ãã®ã©ã¤ãã©ãªå ã®éçå¤æ°
èªã¿è¾¼ã¿å ã®ã¯ã©ã¹ã»ã¢ã¸ã¥ã¼ã«å
æ¡å¼µã©ã¤ãã©ãªå
ã§ã¯ã©ã¹ãã¢ã¸ã¥ã¼ã«ãå®ç¾©ããå ´åãé常㯠rb_define_module("Foo")
ãªã©ã¨å®ç¾©ããããã®å ´åã Foo
㯠Object
ã®ä¸ã«å®ç¾©ãããã
ããã¯ãnamespaceå
ã§ã¯ rb_define_module_under(ns, "Foo")
ãªã©ã¨èªã¿æ¿ãããããªä»çµã¿ãå
¥ããã°ããã ããã
ã·ã³ãã«è§£æ±º
æ¡å¼µã©ã¤ãã©ãªãä»ã®ã©ã¤ãã©ãªã®ã·ã³ãã«ãå
·ä½çã«ã¯é¢æ°ãå¤æ°ãç¨ãã¦ããå ´åãååãè¡çªãã¦ãã¾ããã¨ããããããã©ã¤ãã©ãªã®ç°ãªããã¼ã¸ã§ã³ãæã¤ã·ã³ãã«ã¯åããã¨ãå¤ãã ãããã¤ã¾ãã·ã³ãã«åãè¡çªãã¦ãã¾ãã
Linuxã«ã¯ãã®ãããªç¶æ³ãé¿ããããã® dlmopen(3)
ã¨ããé¢æ°ãããããã¼ã¿ãã«ã§ã¯ãªãã
å¤å°ã®å¯ä½ç¨ã¯ãããããããã解決ç㯠dlopen
ã¸ã®å¼æ°ã« RTLD_GLOBAL
ã§ã¯ãªã RTLD_LOCAL
ãæå®ãããã¨ã¨æãããããã®å ´åãä»ã®æ¡å¼µã©ã¤ãã©ãªãããã®æ¡å¼µã©ã¤ãã©ãªã®ã·ã³ãã«ãè¦ããªããªããå
·ä½ä¾ã 㨠libv8.gem ã®ãããªgemãããã«ãããããã®ãããªæ²»å®ã®æªãgemã¯ããã¾ã§æ°ã¯å¤ããªãã¨ã¯æããâ¦ã
éçå¤æ°
DLLå ã®éçå¤æ°ã®å¤ãå¤æ´ã§ããå ´åãããnamespaceå ã§ã®å¤æ´ãå¥ã®namespaceã«æ³¢åãã¦ãã¾ããä¾ãã°ãmorisããã®æãã¦ããojã®è¨å®ã®ä¾ã§ã¯ãè¨å®æ å ±ã¯ã©ã¤ãã©ãªå ã®éçå¤æ°ã«ä¿åããã¦ããã ããã対çãããã¨æãå ´åãåä¸ã®gemãè¤æ°åã¡ã¢ãªä¸ã®å¥ã®å ´æã«ãã¼ãããå¿ è¦ãããããã«æããããç´ ç´ã«dlopenã使ãã¨ããã¯ã§ããªãã®ã§ãå¥ã®å ´æã«DLLãã³ãã¼ãããªã©ã®å¯¾çãã¨ããã¨ã«ãªãããåã®ã¡ã¢ãªãæ¶è²»ãããã¨ã«ãªãã®ã§å¯ä½ç¨ã大ããã ã¯ã©ã¹å¤æ°ãªãRubyå´ã§ç®¡çãã¦ããé åã«ä¿åããããã«ãgemèªä½ãå¤æ´ãã¦ãããããã«ããã®ãç¡é£ãããããªãã
ã¾ã¨ã
æ¡å¼µã©ã¤ãã©ãªã®namespace対å¿ã«ãããåé¡ã¯ãRubyå´ã®åé¡ã¨ãDLLå´ã®åé¡ã«åé¡ã§ããå¾è ã®å¶ç´ã¯çªç ´ãããã¨ãé£ããããã®å¶ç´ã®ä¸ã§ããããªãã«ä¸å®ã®æ©è½ãæã£ããã®ã¯åºæ¥ãããªãã¨ãã¾ã¨ãã¾ããã