はじめに
この記事は、Opal (Ruby-to-JavaScript compiler) Advent Calendar 2018 の5日目の記事です。
以前書いた、RailsでDXOpalを使ってみたの時の経験をベースに、Rails と Vue.js でDXOpalのオンライン環境っぽいものを作ってみました
つくったもの
デモ
デモにはこちらのソースコードを使用させていただきました。
誠にありがとうございます。
実装など
Webpackerを使い、Vue.jsでフロントエンド、Railsでバックエンドをそれぞれ実装している。
/api/sources
というAPIを作成し、axios
経由でフロントエンドからDXOpalのソースコードをやり取りしている。
エディター部分は vue2-ace-editorにて実装。
実装で一番苦労したのが、DXOpalのソースコードをAPIを経由し、どうやって受け取るか
まず、コントローラーを以下のように変更
class Api::SourcesController < ApplicationController
before_action :set_source, only: [:code, :show, :edit, :hashtags, :update, :destroy]
#省略
def code
render json: @source.code
end
#省略
private
# Use callbacks to share common setup or constraints between actions.
def set_source
@source = Source.find(params[:id])
end
# 以下省略
end
Rails.application.routes.draw do
#省略
namespace :api, format: 'json' do
resources :sources
get "/sources/:id/code", to: "sources#code"
end
end
code
というアクションを作成し、/api/sources/:id/code
というルーティングを追加。
あとは、DXOpalのソースコードを実行する各Showページを下記のように変更
<template>
<div class="container">
<h1><p> Name: {{name}} </p></h1>
<h2><p> Code </p></h2>
<p>{{code}}</p>
<h2><p> Game </p></h2>
<script type="text/ruby">
require 'native'
DXOpal.dump_error{ require_remote "/api/" + String($$.location.pathname) + "/code" }
</script>
<canvas id="dxopal-canvas"></canvas>
<div id="dxopal-errors"></div>
<input type='button' id='pause' value='Pause/Resume'>
</div>
</template>
肝は、下記の部分。
require 'native'
DXOpal.dump_error{ require_remote "/api/" + String($$.location.pathname) + "/code" }
まず、require
native``で$$.location.pathname
が使えるようにする。
そのあと、以下のコードで、/api/sources/:id/code
にアクセスし、DXOpalのソースコードを読み取り実行
DXOpal.dump_error{ require_remote "/api/" + String($$.location.pathname) + "/code" }
これで、DXOpalの実行が確認できる
おわりに
まだ基礎的な部分しか出来上がっていないので、まずはデザインなどをよしなにしていきたいと思う。
あと、実際にコーディングしている際に実行して確認できるような環境構築もしていきたいと思う。