Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Writing simple and easy DSL with Ruby

Writing simple and easy DSL with Ruby

110cd4dcaed019b3bd9809e541afdeb6?s=128

Masafumi Okura

January 29, 2022
Tweet

More Decks by Masafumi Okura

Other Decks in Programming

Transcript

  1. RubyͰ࡞ΔSimpleͰEasyͳ DSL Burikaigi 2022 ϧʔϜϗλϧΠΧ OKURA Masafumi, 2022

  2. Ruby DSL

  3. DSLͱ͸ʁ

  4. None
  5. Ҏ߱ͷ”DSL”͸ʮݴޠ಺DSLʯΛࢦ͢ ͜ͱͱ͠·͢

  6. RubyͰॻ͔ΕͨDSLͷྫʢRuby಺Ͱͷར༻ʣ • Rake • RSpec • FactoryBot • Sinatra •

    Rails • ίʔϧόοΫɺόϦσʔγϣϯͳͲ
  7. RSpecͷྫʢREADMEΑΓʣ

  8. RubyͰॻ͔ΕͨDSLͷྫʢRuby֎Ͱͷར༻ʣ • Homebrew • Chef • Vagrant • Capistrano

  9. HomebrewͷྫʢZoomͷCaskΑΓʣ

  10. ݴޠ಺DSLͷϝϦοτ • ϓϩάϥϛϯάݴޠͷϑϧػೳ͕࢖͑Δ • ม਺΍ؔ਺ • ಡΉ͚ͩͳΒϓϩάϥϛϯάݴޠͷ஌͕ࣝෆཁ • ϓϩάϥϛϯάݴޠͱઃఆϑΝΠϧͷ͍͍ͱ͜औΓ

  11. ࣗݾ঺հ • ໊લɿେ૔խ࢙ • ॴଐɿϑϦʔϥϯε • ՝֎׆ಈɿKaigi on RailsνʔϑΦʔΨφΠβʔɺGrow.rb/Entaku.rb ΦʔΨφΠβʔɺAlba࡞ऀ

    • ޷͖ͳRubyͷϝιουɿinstance_evalʢ2೥લͷൃදΛࢀরʣ
  12. Alba • JSONγϦΞϥΠβʢ೚ҙͷΦϒδΣΫτΛJSONʹม׵ʣ • ଎͍ʢྨࣅͷgemͱൺ΂ͯ΋2൪໨ʹ଎͍ʣ • ໿300ms͔͔͍ͬͯͨAPIΛ໿100ms·Ͱߴ଎Խͨ͠Γ • Ϣʔβʔ͕DSLΛॻ͘ͱAlba͕ͦΕʹैͬͯΦϒδΣΫτ͔ΒଐੑΛऔಘ ͯ͠JSONΛߏங͢Δ

    • ৄࡉ͸ https://github.com/okuramasafumi/alba Λࢀর
  13. ࠓ೔ͷൃද ͷߏ੒

  14. ೋ෦ߏ੒ • ୈҰ෦ɿDSLʹؔ͢Δཧ࿦తߟ࡯ • RubyͱDSLɺϑΣʔζͷ෼཭ͳͲ • ୈೋ෦ɿDSLΛ࡞ͬͯΈΔ • ؆୯ͳDSLΛ࡞ͬͯΈΔ •

    ࣮૷͕SimpleͰ࢖͍ํ͕EasyͳDSLΛ࡞Δ • λΠτϧճऩ
  15. ୈҰ෦ɿ DSLʹ͍ͭͯͷ ߟ࡯

  16. ͳͥRubyͰ DSLΛॻ͘ͷ͔

  17. RubyͰDSLΛॻ͘ཧ༝ • τοϓϨϕϧʢRubyͰ͸”main”ʣʹϝιουΛఆٛ͠΍͍͢ • ϝιουͷׅހ͕লུͰ͖ΔͷͰݟͨ໨͕ӳจͬΆ͘ͳΓ΍͍͢ • => ಡΈ΍͍͢ • ωετͨ͠ϒϩοΫͱ”eval”଒ϝιουͷ૊Έ߹ΘͤΛ࢖͏͜ͱͰෳ

    ࡶͳϩδοΫ΋දݱͰ͖Δ • => ॻ͖΍͍͢
  18. ٯʹݴ͏ͱ • DSL͸୯ͳΔϝιουʢಛʹΫϥεϝιουʣ • eval଒ͱϒϩοΫͷ࢖͍ํ͑͞Θ͔Ε͹DSL͸࡞ΕΔʂ

  19. Rubyʹ͓͚ΔDSLͷ෼ྨʹ͍ͭͯ • “main”ύλʔϯɿ”main”ʹ௚઀ϝιουΛఆٛ͢Δύλʔϯ • Rake, SinatraͳͲ • “include”ύλʔϯɿϞδϡʔϧ಺ʹσʔλͱϩδοΫΛू໿͠ɺ`include`΍`extend`͠ ͨΫϥε͕ͦΕʹΞΫηεͰ͖Δύλʔϯ •

    Railsͷଟ͘ͷDSL • ಠཱύλʔϯɿϞδϡʔϧΛ`include`͠ͳͯ͘΋DSLΛ࢖͑Δ • RSpec, FactoryBotͳͲ
  20. DSLͷ࣮૷্ͷίπ • ʮఆٛɾొ࿥ʯʮࢦఆʯʮ࣮ߦʯͷϑΣʔζ͕෼͔Ε͍ͯΔͨΊɺ͜ ΕΒΛ͔ͬ͠Γ෼཭্ͭͭ͠खʹ݁߹͢Δ • ʮఆٛɾొ࿥ʯϑΣʔζͰ͸ʮ࣮ߦʯϑΣʔζͰߦ͍͍ͨ͜ͱΛొ࿥ ͍ͯ͘͠ • ʮࢦఆʯϑΣʔζͰ͸ʮఆٛɾొ࿥ʯ͞Εͨ΋ͷ͔Βࠓճద༻͍ͨ͠ ΋ͷΛࢦఆ͢Δ

    • ʮ࣮ߦʯϑΣʔζͰ͸ʮࢦఆʯ͞Εͨ΋ͷΛ࣮ߦ͢Δ
  21. ݱ࣮ͷDSLʹ͓͚ΔϑΣʔζͷ෼཭ ఆٛ ࢦఆ ࣮ߦ 3BLF UBTL EFGBVMUͳͲ SBLFίϚϯυ 34QFD EFTDSJCF

    JUͳͲ  STQFDίϚϯυ 3BJMTόϦσʔγϣϯ A"DUJWF.PEFM7BMJEBUPSAΫ ϥεΛܧঝͨ͠Ϋϥεͷ࡞੒ WBMJEBUFTϝιου WBMJE ϝιου "MCB A"MCB3FTPVSDFAϞδϡʔϧ ΛAJODMVEFA͔ͯ͠Β ABUUSJCVUFTAͳͲ Ϋϥεબ୒ TFSJBMJ[Fϝιου
  22. ࠓճ࡞ΔDSLʹ͍ͭͯ • ΍Γ͍ͨ͜ͱɿRailsͷόϦσʔγϣϯͷ؆қ൛ • ࣮૷ɿϞδϡʔϧΛ`include`͢ΔͱɺΫϥεϝιουͷ`.validates`ͱ Πϯελϯεϝιουͷ`#validate`͕ར༻ՄೳʹͳΔ • `.validates`ʹ͸όϦσʔλͷ໊લͱΦϓγϣϯΛ౉͢ɺ͢ΔͱόϦ σʔλ͕Ϋϥεʹొ࿥͞ΕΔ •

    `#validate`͸ࣗ਎ͷΫϥεʹొ࿥͞ΕͨόϦσʔλΛ࣮ߦ͢Δ
  23. ʢଓʣࠓճ࡞ΔDSLʹ͍ͭͯ • ॳظঢ়ଶͰ͸όϦσʔλ͕ଘࡏ͠ͳ͍ͨΊɺ`.validator`ϝιουͰఆ ͍ٛͯ͘͠ • ޙͰ`.validates`Ͱࢦఆ͢ΔͨΊͷ໊લͱɺϩδοΫʢόϦσʔγϣ ϯͷ಺༰ʣΛఆٛ͢Δ • ϩδοΫ͸ϒϩοΫͰఆٛ͢Δɺ͜ͷͱ͖ର৅ͷΦϒδΣΫτͱඞ ཁͳ஋ʢ௕͞ΛόϦσʔτ͢ΔͳΒͦͷ਺ࣈʣΛड͚औΔ

  24. ͓·͚ͷߟ࡯ • ϓϩάϥϛϯάͰ͸ʮߏ଄ʯͱʮৼΔ෣͍ʯͷ2͕ͭॏཁ • cf. σβΠϯύλʔϯͷ෼ྨ • ʮఆٛɾొ࿥ʯͱʮࢦఆʯ͸ߏ଄Ͱʮ࣮ߦʯ͸ৼΔ෣͍ • ߏ଄͸੩తͰৼΔ෣͍͸ಈతɺͱ΋͍͑Δ

    • DSLΛ࢖͏ͱߏ଄ͱৼΔ෣͍Λࣗવʹ෼཭Ͱ͖ͯݟ௨͕͠ྑ͘ͳΔ
  25. ୈೋ෦ɿ ࣮ࡍʹDSLΛ ࡞ͬͯΈΑ͏ʂ

  26. ΤσΟλ͕։ ͖·͢