Skip to content

Commit

Permalink
Merge pull request #65 from keyasuda/evalasync
Browse files Browse the repository at this point in the history
use evalAsync to use JS::Object#await
  • Loading branch information
keyasuda committed Jan 2, 2023
2 parents 8646794 + 0dc05f5 commit 29f1534
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 26 deletions.
2 changes: 1 addition & 1 deletion gem/lib/bormashino/ext/js.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module JS
# extends ruby.wasm JS::Object to intract with JS
class Object
def to_rb
JSON.parse(JS.global[:JSON].call(:stringify, self).inspect)
JSON.parse(JS.global[:JSON].call(:stringify, self).to_s)
end
end
end
2 changes: 2 additions & 0 deletions gem/lib/bormashino/fetch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ class Fetch
attr_accessor :resource, :init, :resolved_to, :options

def initialize(resource:, resolved_to:, init: {}, options: {})
JS.eval("console.warn('Bormashino::Fetch is deprecated. Use Fetch API and JS::Object#await')")

@resource = resource
@init = init
@resolved_to = resolved_to
Expand Down
41 changes: 21 additions & 20 deletions npm/src/ruby.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,19 @@ const currentPath = () => location.href.replace(location.origin, '')
export const router = hr
export const mount = () => router.always(() => request('get', currentPath()))

export const request = (
export const request = async (
method,
path,
payload = '',
referer = currentPath()
) => {
const target = document.querySelector('#bormashino-application')

const ret = requestToServer(method, path, payload, referer)
const ret = await requestToServer(method, path, payload, referer)
if (applyServerResult(JSON.parse(ret.toJS()), target, router))
hookTransitionElements(target, request)
}

// JSでの値をRubyでの値に変換する
// JS obj -> JSON -> url-encoded str -> (vm.eval) -> JSON -> Ruby obj
const toRbValue = (v) => {
const input = "'" + encodeURIComponent(JSON.stringify(v)) + "'"
return vm
.eval('JSON')
.call('parse', vm.eval('CGI').call('unescape', vm.eval(input)))
}

export const initVm = async (
rubyUri,
initializeOption = ['ruby.wasm', '-I/stub', '-EUTF-8', '-e_=0']
Expand All @@ -47,6 +38,9 @@ export const initVmFromRubyModule = async (
) => {
const wasmFs = new WasmFs()
const wasi = new WASI({
env: {
RUBY_FIBER_MACHINE_STACK_SIZE: String(1024 * 1024 * 20),
},
bindings: Object.assign(Object.assign({}, WASI.defaultBindings), {
fs: wasmFs.fs,
}),
Expand Down Expand Up @@ -93,15 +87,22 @@ export const initVmFromRubyModule = async (
return vm
}

const requestToServer = (method, path, payload, referer) => {
const server = vm.eval('Bormashino::Server')
const ret = server.call(
'request',
toRbValue(method.toUpperCase()),
toRbValue(path),
toRbValue(payload),
toRbValue(referer)
)
const requestToServer = async (method, path, payload, referer) => {
window.bormashino.requestSrc = JSON.stringify({
method,
path,
payload,
referer,
})
const ret = await vm.evalAsync(`
src = JSON.parse(JS.global[:window][:bormashino][:requestSrc].to_s)
Bormashino::Server.request(
src['method'].upcase,
src['path'],
src['payload'],
src['referer']
)
`)

return ret
}
6 changes: 3 additions & 3 deletions test-app/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ const main = async () => {
'dispatched: ' + Number(new Date())
})

window.bormashino = RubyApplication
window.rubyVM = vm

const currentPath = () => location.href.replace(location.origin, '')
RubyApplication.request('get', currentPath())
RubyApplication.mount()

window.bormashino = RubyApplication
window.rubyVM = vm
}

main()
11 changes: 10 additions & 1 deletion test-app/spec/test_app_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
it { is_expected.to have_text('2nd form has submitted') }
end

describe 'fetch api' do
describe 'Bormashino::Fetch' do
before do
click_link 'fetch test'
sleep 1
Expand All @@ -71,6 +71,15 @@
it { is_expected.to have_text('{"status"=>"200", "payload"=>"fetched text\n", "options"=>"{\"param1\":\"value1\",\"param2\":\"value2\"}"}') }
end

describe 'async/await' do
before do
click_link 'JS::Object#await fetch'
sleep 1
end

it { is_expected.to have_text('fetched text') }
end

describe 'LocalStorage' do
before do
click_link 'localstorage test'
Expand Down
6 changes: 6 additions & 0 deletions test-app/src/app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ class App < Sinatra::Base
'initiated'
end

get '/fetch2' do
result = JS.global.fetch('/fetch.txt').await
ret = result.text.await
ret.to_s
end

post '/fetched' do
params.inspect
end
Expand Down
3 changes: 2 additions & 1 deletion test-app/src/views/index.erb
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<h1>ruby appが初期化されました。</h1>

<p><a href="/link" id="get-link">link</a></p>
<p><a href="/fetch">fetch test</a></p>
<p><a href="/fetch">fetch test</a>(Bormashino::Fetch)</p>
<p><a href="/fetch2">JS::Object#await fetch</a></p>

<div>
<form action="/form-submit" method="put">
Expand Down

0 comments on commit 29f1534

Please sign in to comment.