livecode-static/docs/assets/js/825a9671.3ef210f5.js
2025-06-11 22:23:49 +08:00

62 lines
17 KiB
JavaScript

"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["2873"],{905:function(e,t,s){s.r(t),s.d(t,{default:()=>m,frontMatter:()=>a,metadata:()=>n,assets:()=>c,params:()=>d,toc:()=>u,contentTitle:()=>l});var n=JSON.parse('{"id":"languages/ruby-wasm","title":"Ruby (Wasm)","description":"Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.","source":"@site/docs/languages/ruby-wasm.mdx","sourceDirName":"languages","slug":"/languages/ruby-wasm","permalink":"/docs/languages/ruby-wasm","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/languages/ruby-wasm.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Riot.js","permalink":"/docs/languages/riot"},"next":{"title":"Ruby","permalink":"/docs/languages/ruby"}}'),r=s("5893"),i=s("65"),o=s("3365");let a={},l="Ruby (Wasm)",c={},d={"ruby-wasm":`class User
attr_accessor :name
def initialize(name)
@name = name
end
def admin?
@name == 'Admin'
end
end
user = User.new('Bob')
# the output will go to the console
puts user
puts user.admin?
`,console:"full"},u=[{value:"Usage",id:"usage",level:2},{value:"Language Info",id:"language-info",level:2},{value:"Name",id:"name",level:3},{value:"Extension",id:"extension",level:3},{value:"Alias",id:"alias",level:3},{value:"Editor",id:"editor",level:3},{value:"Compiler",id:"compiler",level:2},{value:"Version",id:"version",level:3},{value:"Code Formatting",id:"code-formatting",level:2},{value:"Example Usage",id:"example-usage",level:2},{value:"Starter Template",id:"starter-template",level:2},{value:"Links",id:"links",level:2}];function h(e){let t={a:"a",admonition:"admonition",blockquote:"blockquote",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",ul:"ul",...(0,i.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.header,{children:(0,r.jsx)(t.h1,{id:"ruby-wasm",children:"Ruby (Wasm)"})}),"\n",(0,r.jsxs)(t.p,{children:[(0,r.jsx)(t.a,{href:"https://ruby-lang.org/",children:"Ruby"})," is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write."]}),"\n",(0,r.jsxs)(t.p,{children:["LiveCodes uses ",(0,r.jsx)(t.a,{href:"https://github.com/ruby/ruby.wasm",children:"ruby.wasm"})," to run Ruby in the browser."]}),"\n",(0,r.jsxs)(t.blockquote,{children:["\n",(0,r.jsxs)(t.p,{children:["ruby.wasm is a collection of ",(0,r.jsx)(t.a,{href:"https://webassembly.org/",children:"WebAssembly"})," ports of the ",(0,r.jsx)(t.a,{href:"https://github.com/ruby/ruby",children:"CRuby"}),". It enables running Ruby application on browsers, WASI compatible WebAssembly runtimes, and Edge Computing platforms."]}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://ruby.github.io/ruby.wasm/",children:"ruby.github.io/ruby.wasm/"})}),"\n"]}),"\n",(0,r.jsx)(t.admonition,{title:"Note",type:"info",children:(0,r.jsxs)(t.p,{children:["LiveCodes also supports running Ruby using ",(0,r.jsx)(t.a,{href:"https://opalrb.com/",children:"Opal"})," which is a Ruby to JavaScript source-to-source compiler. Read documentation ",(0,r.jsx)(t.a,{href:"/docs/languages/ruby",children:"here"}),"."]})}),"\n",(0,r.jsx)(t.h2,{id:"usage",children:"Usage"}),"\n",(0,r.jsx)(t.p,{children:"LiveCodes runs Ruby in the browser, including the stdlib."}),"\n",(0,r.jsxs)(t.p,{children:["JavaScript interoperability and DOM access is achieved using ",(0,r.jsxs)(t.a,{href:"https://ruby.github.io/ruby.wasm/JS.html",children:[(0,r.jsx)(t.code,{children:'"JS"'})," module"]}),". See the ",(0,r.jsx)(t.a,{href:"#starter-template",children:"starter template"})," for an example."]}),"\n",(0,r.jsx)(t.h2,{id:"language-info",children:"Language Info"}),"\n",(0,r.jsx)(t.h3,{id:"name",children:"Name"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"ruby-wasm"})}),"\n",(0,r.jsx)(t.h3,{id:"extension",children:"Extension"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:".wasm.rb"})}),"\n",(0,r.jsx)(t.h3,{id:"alias",children:"Alias"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"rubywasm"})}),"\n",(0,r.jsx)(t.h3,{id:"editor",children:"Editor"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"script"})}),"\n",(0,r.jsx)(t.h2,{id:"compiler",children:"Compiler"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://github.com/ruby/ruby.wasm",children:"ruby.wasm"})}),"\n",(0,r.jsx)(t.h3,{id:"version",children:"Version"}),"\n",(0,r.jsx)(t.p,{children:"ruby.wasm v2.6.2, running Ruby v3.3"}),"\n",(0,r.jsx)(t.h2,{id:"code-formatting",children:"Code Formatting"}),"\n",(0,r.jsx)(t.p,{children:"Not supported for Ruby."}),"\n",(0,r.jsx)(t.h2,{id:"example-usage",children:"Example Usage"}),"\n","\n","\n",(0,r.jsx)(o.Z,{params:d,height:"80vh"}),"\n",(0,r.jsx)(t.p,{children:"This example demonstrates stdlib usage, JavaScript interoperability and DOM access:"}),"\n",(0,r.jsx)(o.Z,{template:"ruby-wasm",height:"80vh"}),"\n",(0,r.jsx)(t.h2,{id:"starter-template",children:"Starter Template"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://livecodes.io/?template=ruby-wasm",children:"https://livecodes.io/?template=ruby-wasm"})}),"\n",(0,r.jsx)(t.h2,{id:"links",children:"Links"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://ruby-lang.org/",children:"Ruby"})}),"\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://ruby-lang.org/en/documentation/",children:"Ruby documentation"})}),"\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://github.com/ruby/ruby.wasm",children:"ruby.wasm"})}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.a,{href:"/docs/languages/ruby",children:"Ruby using Opal"})," in LiveCodes"]}),"\n"]})]})}function m(e={}){let{wrapper:t}={...(0,i.a)(),...e.components};return t?(0,r.jsx)(t,{...e,children:(0,r.jsx)(h,{...e})}):h(e)}},3365:function(e,t,s){s.d(t,{Z:()=>y});var n=s("5893"),r=s("4200"),i=s("7294"),o=s("8294");function a(e){let t=(0,i.useRef)(null),[s,r]=(0,i.useState)(e.className||""),[a,l]=(0,i.useState)(e.style||{}),[c,d]=(0,i.useState)(e.height),[u,h]=(0,i.useState)(),[m,p]=(0,i.useState)(JSON.stringify(e.config||"")),[g,y]=(0,i.useState)("");return(0,i.useEffect)(()=>{if(!t.current)return;let{className:s,style:n,height:i,sdkReady:a,config:c,...f}=e;if(r(s||""),l(n||{}),d(i),u&&g===JSON.stringify(f)){if(m===JSON.stringify(c))return;p(JSON.stringify(c)),"string"==typeof c?fetch(c).then(e=>e.json()).then(e=>{u?.setConfig(e)}):c&&u.setConfig(c)}else y(JSON.stringify(f)),u?.destroy(),(0,o.T)(t.current,{config:c,...f}).then(e=>{h(e),"function"==typeof a&&a(e)})},[e]),(0,i.useEffect)(()=>()=>{u?.destroy()},[]),(0,n.jsx)("div",{ref:t,className:s,style:a,"data-height":c})}var l=s("1858"),c=s("3262"),d=s("1705"),u=s("7645"),h=s("8168"),m=s("8228"),p=s("5050");function g(e){let[t,s]=(0,i.useState)(e.js),[r,o]=(0,i.useState)(e.ts),[a,l]=(0,i.useState)(e.react),[g,y]=(0,i.useState)(e.vue),[f,b]=(0,i.useState)(e.svelte),v="3.7rem",[x,w]=(0,i.useState)(!0),[j,S]=(0,i.useState)(v),C=(0,i.useRef)(null),E=()=>{setTimeout(()=>{S(`calc(${C.current.offsetHeight}px + ${v})`)},5),setTimeout(()=>{S(`calc(${C.current.offsetHeight}px + ${v})`)},255)};return(0,i.useEffect)(()=>{if(c.Z.canUseDOM){let e=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"js";try{return window.prettier?.format(e,{parser:"html"===t?"html":"babel",plugins:window.prettierPlugins})}catch{return e}};s(e(t,"js")),o(e(r,"ts")),l(e(a,"jsx")),y(e(g,"html")),b(e(f,"html"))}},[]),(0,n.jsxs)("details",{className:`alert alert--info ${p.Z.details} ${m.Z.details}`,"data-collapsed":x,style:{height:x?v:j,overflow:"hidden",willChange:"height",transition:`height ${x?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,n.jsx)("summary",{onClick:()=>{w(!x),E()},children:"show code"}),(0,n.jsx)("div",{ref:C,style:{display:"block",overflow:"hidden"},children:(0,n.jsx)("div",{className:p.Z.collapsibleContent,children:(0,n.jsxs)(h.Z,{groupId:"sdk-code",children:[(0,n.jsx)(u.Z,{value:"js",label:"JS",attributes:{onMouseDown:E},children:(0,n.jsx)(d.Z,{language:"js",children:t})}),(0,n.jsx)(u.Z,{value:"ts",label:"TS",attributes:{onMouseDown:E},children:(0,n.jsx)(d.Z,{language:"ts",children:r})}),(0,n.jsx)(u.Z,{value:"react",label:"React",attributes:{onMouseDown:E},children:(0,n.jsx)(d.Z,{language:"jsx",children:a})}),(0,n.jsx)(u.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:E},children:(0,n.jsx)(d.Z,{language:"html",children:g})}),(0,n.jsx)(u.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:E},children:(0,n.jsx)(d.Z,{language:"html",children:f})})]})})})]})}function y(e){let{className:t,style:s,showCode:i,height:o,...c}=e,{colorMode:d}=(0,r.I)(),u=e=>JSON.stringify(e,null,2),h=`
import { createPlayground } from 'livecodes';
const options = ${u(c)};
createPlayground('#container', options);
`.trimStart(),m=`
import { createPlayground, type EmbedOptions } from 'livecodes';
const options: EmbedOptions = ${u(c)};
createPlayground('#container', options);
`.trimStart(),p=`
import LiveCodes from 'livecodes/react';
export default function App() {
const options = ${u(c)};
return (<LiveCodes {...options}></LiveCodes>);
}
`.trimStart(),y=`
<script setup>
import LiveCodes from "livecodes/vue";
const options = ${u(c)};
</script>
<template>
<LiveCodes v-bind="options" />
</template>
`,f=`
<script>
import { onMount } from 'svelte';
import { createPlayground } from 'livecodes';
let options = $state(${u(c)});
let container = $state(null);
onMount(() => {
createPlayground(container, options);
});
</script>
<div bind:this="{container}"></div>
`.trimStart();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(a,{className:`container_Egsj ${e.className}`,style:{height:o||"50vh",...e.style},appUrl:l.G,...e,config:{theme:d,themeColor:"hsl(215, 8%, 60%)",..."object"==typeof e.config?e.config:{}}}),!1!==e.showCode&&(0,n.jsx)(g,{js:h,ts:m,react:p,vue:y,svelte:f})]})}},8294:function(e,t,s){s.d(t,{T:function(){return r},r:function(){return i}});var n=s(7728);async function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"object"!=typeof e||e instanceof HTMLElement||!e.headless&&"headless"!==e.view||(t=e,e=null);let{config:s={},headless:n,loading:r="lazy",view:o}=t,a=n||"headless"===o,l=null,c=null;if("string"==typeof e)l=document.querySelector(e);else if(e instanceof HTMLElement)l=e;else if(!(a&&"object"==typeof e))throw Error("A valid container element is required.");if(!l){if(a)E(l=document.createElement("div")),document.body.appendChild(l);else throw Error(`Cannot find element: "${e}"`)}let d=new URL(i(t)),u=d.origin;d.searchParams.set("embed","true"),d.searchParams.set("loading",a?"eager":r);let h=globalThis.process;d.searchParams.set("sdkVersion",h?.env?.SDK_VERSION||"latest"),"object"==typeof s&&Object.keys(s).length>0&&d.searchParams.set("config","sdk");let m=t.params;"object"==typeof m&&Object.keys(m).length>0&&JSON.stringify(m).length<1800&&Object.keys(m).forEach(e=>{d.searchParams.set(e,encodeURIComponent(String(m[e])))});let p=!1,g="Cannot call API methods after calling `destroy()`.",y=await new Promise(e=>{if(!l)return;let t=l.dataset.height||l.style.height;if(t&&!a){let e=isNaN(Number(t))?t:t+"px";l.style.height=e}"false"===l.dataset.defaultStyles||a||(l.style.backgroundColor||="#fff",l.style.border||="1px solid black",l.style.borderRadius||="8px",l.style.boxSizing||="border-box",l.style.padding||="0",l.style.width||="100%",l.style.height||=l.style.height||"300px",l.style.minHeight="200px",l.style.flexGrow="1",l.style.overflow||="hidden",l.style.resize||="vertical");let n="livecodes",i=l.querySelector(`iframe.${n}`),o=i||document.createElement("iframe");o.classList.add(n),o.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),o.setAttribute("allowtransparency","true"),o.setAttribute("allowpaymentrequest","true"),o.setAttribute("allowfullscreen","true"),o.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),o.setAttribute("loading","eager"===r?"eager":"lazy"),a?E(o):(o.style.height="100%",o.style.minHeight="200px",o.style.width="100%",o.style.margin="0",o.style.border="0",o.style.borderRadius=l.style.borderRadius),addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===u&&t.data?.type==="livecodes-init"&&(removeEventListener("message",e),c=Number(t.data.payload.appVersion.replace(/^v/,"")))}),(!c||c<46)&&addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===u&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),o.contentWindow?.postMessage({type:"livecodes-config",payload:s},u))}),o.onload=()=>{e(o)},o.src=d.href,i||l.appendChild(o)}),f=new Promise(e=>{addEventListener("message",function t(s){s.source===y.contentWindow&&s.origin===u&&s.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),f.settled=!0)})}),b=()=>p?Promise.reject(g):new Promise(async e=>{f.settled&&e(),y.contentWindow?.postMessage({type:"livecodes-load"},u),await f,e()}),v=(e,t)=>new Promise(async(s,n)=>{if(p)return n(g);await b();let r=R();addEventListener("message",function t(i){if(i.source===y.contentWindow&&i.origin===u&&i.data?.type==="livecodes-api-response"&&i.data?.id===r&&i.data.method===e){removeEventListener("message",t);let e=i.data.payload;e?.error?n(e.error):s(e)}}),y.contentWindow?.postMessage({method:e,id:r,args:t},u)}),x={},w=["load","ready","code","console","tests","destroy"],j=(e,t)=>{if(p)throw Error(g);return w.includes(e)?(v("watch",[e]),x[e]||(x[e]=[]),x[e]?.push(t),{remove:()=>{x[e]=x[e]?.filter(e=>e!==t),x[e]?.length===0&&v("watch",[e,"unsubscribe"])}}):{remove:()=>void 0}},S=e=>({"livecodes-app-loaded":"load","livecodes-ready":"ready","livecodes-change":"code","livecodes-console":"console","livecodes-test-results":"tests","livecodes-destroy":"destroy"})[e];addEventListener("message",async e=>{let t=S(e.data?.type??"");if(e.source!==y.contentWindow||e.origin!==u||!t||!x[t])return;let s=e.data?.payload;x[t]?.forEach(e=>{e(s)})});let C=()=>{Object.values(x).forEach(e=>{e.length=0}),y?.remove?.(),p=!0};function E(e){e.style.position="absolute",e.style.top="0",e.style.visibility="hidden",e.style.opacity="0"}"lazy"===r&&"IntersectionObserver"in window&&new IntersectionObserver((e,t)=>{e.forEach(async e=>{e.isIntersecting&&(await b(),t.unobserve(l))})},{rootMargin:"150px"}).observe(l);let R=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>b(),run:()=>v("run"),format:e=>v("format",[e]),getShareUrl:e=>v("getShareUrl",[e]),getConfig:e=>v("getConfig",[e]),setConfig:e=>v("setConfig",[e]),getCode:()=>v("getCode"),show:(e,t)=>v("show",[e,t]),runTests:()=>v("runTests"),onChange:e=>j("code",e),watch:j,exec:function(e){for(var t=arguments.length,s=Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];return v("exec",[e,...s])},destroy:()=>f.settled?v("destroy").then(C):p?Promise.reject(g):(C(),Promise.resolve())}}function i(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:s="https://livecodes.io",params:r={},config:i={},headless:o,import:a,lite:l,view:c,...d}=t;try{e=new URL(s)}catch{throw Error(`${s} is not a valid URL.`)}let u=new URLSearchParams;Object.entries(d).forEach(t=>{let[s,n]=t;void 0!==n&&e.searchParams.set(s,String(n))});let h="headless"===t.view||o;if(l&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof i&&null==i.mode?i.mode="lite":e.searchParams.set("lite","true")),c&&(console.warn('Deprecation notice: The "view" option has been moved to "config.view". For headless mode use "headless: true".'),"object"==typeof i&&null==i.view&&"headless"!==c?i.view=c:e.searchParams.set("view",c)),"string"==typeof i)try{new URL(i),e.searchParams.set("config",encodeURIComponent(i))}catch{throw Error('"config" is not a valid URL or configuration object.')}else i&&"object"==typeof i&&Object.keys(i).length>0&&(i.title&&"Untitled Project"!==i.title&&e.searchParams.set("title",i.title),i.description&&i.description.length>0&&e.searchParams.set("description",i.description),u.set("config","code/"+(0,n.compressToEncodedURIComponent)(JSON.stringify(i))));if(r&&"object"==typeof r&&Object.keys(r).length>0)try{u.set("params",(0,n.compressToEncodedURIComponent)(JSON.stringify(r)))}catch{Object.keys(r).forEach(t=>{e.searchParams.set(t,encodeURIComponent(String(r[t])))})}return a&&e.searchParams.set("x",encodeURIComponent(a)),h&&e.searchParams.set("headless","true"),e.hash=u.toString(),e.href}},65:function(e,t,s){s.d(t,{Z:function(){return a},a:function(){return o}});var n=s(7294);let r={},i=n.createContext(r);function o(e){let t=n.useContext(i);return n.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function a(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:o(e.components),n.createElement(i.Provider,{value:t},e.children)}}}]);