0
votes

I want to use javascript in Ruby on Rails framework, but it does not show any effect.

I made a html file connect with javascript. It works by double-clicking the html file and can see the javascript result.

But when I tried to put them into Ruby on Rails. I have no idea where shall I put the javascript in.

I created a new rails app with controller pages and views/pages/home.html.erb and assets/javascripts/pages.coffee. I put the html code into the pages/home.html.erb but where shall I put the javascript in- javascripts/application.js or javascripts/pages.coffee or created a new xx.js file? How to make it work? I tried to put the js code in the above, but it does not work at all. [![enter image description here][1]][1][![enter image description here][2]][2][![enter image description here][3]][3]


Pre-work I have done but not had any effect 1. Ruby on Rails-4.2 2. Have added the two gems - gem 'execjs' - gem 'therubyracer' 3. Assets/javascripts/application.js - require jquery - require jquery_ujs - require turbolinks - require_tree . 4. Installed processingjs - gem install processingjs 5. Installed node.js

require jquery
require jquery_ujs
require turbolinks
require_tree .

var jsMain = function(processingInstance){ with (processingInstance){
size(400, 400);  // set size of canvas

// add your code here ...
background(255, 0, 0);

}};
<!DOCTYPE html>
<html>
<head>
<title>Playproject</title>
</head>
<body>

<h1>Playproject 2</h1>

<h1>
<canvas id="pageCanvas"></canvas>
</h1>

<p align="center">
	<canvas id="mycanvas"></canvas>
</p>

</body>

<script src="../processing-1.4.8.min.js"></script>
<script src="/assets/javascripts/application.js"></script>
<script type="application/javascript">

var canvas = document.getElementById("mycanvas");
var processingInstance = new Processing(canvas, jsMain);

</script>
</html>
1

1 Answers

1
votes

The answer is put javascript in html for the present. But I think you may put javascript code in assets/javascript/pages.coffee.

You need use app/views/layouts/appliaction.html.erb because application.js need compile.

How about this?

$ rails g controller pages

app/controllers/pages_controller.rb

class PagesController < ApplicationController
  def home
  end
end

config/routes.rb

get 'pages/home' => 'pages#home'

appliation.js not changed.

downloadprocessing.js and put app/assets/javasctipts/

http://processingjs.org/

app/views/pages/home.html.erb

<h1>Playproject 2</h1>

<h1>
<canvas id="pageCanvas">canvas</canvas>
</h1>

<p align="center">
    <canvas id="mycanvas"></canvas>
</p>

</body>

<script type="application/javascript">
var canvas = document.getElementById("mycanvas");

var jsMain = function(processingInstance){ with (processingInstance){
  size(400, 400);
  background(255, 0, 0);
}};

var processingInstance = new Processing(canvas, jsMain);

</script>

enter image description here