LoginSignup
2
0

More than 3 years have passed since last update.

DXOpalをオンラインでコーディング&実行できるようにしてみた

Last updated at Posted at 2018-12-04

はじめに

この記事は、Opal (Ruby-to-JavaScript compiler) Advent Calendar 2018 の5日目の記事です。

以前書いた、RailsでDXOpalを使ってみたの時の経験をベースに、Rails と Vue.js でDXOpalのオンライン環境っぽいものを作ってみました

つくったもの

デモ

dxopaleditor.gif

デモにはこちらのソースコードを使用させていただきました。
誠にありがとうございます。

ソースコード

実装など

Webpackerを使い、Vue.jsでフロントエンド、Railsでバックエンドをそれぞれ実装している。

/api/sourcesというAPIを作成し、axios経由でフロントエンドからDXOpalのソースコードをやり取りしている。

エディター部分は vue2-ace-editorにて実装。

実装で一番苦労したのが、DXOpalのソースコードをAPIを経由し、どうやって受け取るか

まず、コントローラーを以下のように変更

api/sources_controller.rb
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
routes.rb
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ページを下記のように変更

Show.vue
<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" }

まず、requirenative`$$.location.pathname`が使えるようにする。

そのあと、以下のコードで、/api/sources/:id/codeにアクセスし、DXOpalのソースコードを読み取り実行

DXOpal.dump_error{ require_remote "/api/" + String($$.location.pathname) + "/code" }

これで、DXOpalの実行が確認できる

おわりに

まだ基礎的な部分しか出来上がっていないので、まずはデザインなどをよしなにしていきたいと思う。

あと、実際にコーディングしている際に実行して確認できるような環境構築もしていきたいと思う。

参考リンク

yhara/dxopal

opal/opal

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0