// some jquery code before alert
alert(<%= I18n.t(:forbidden_message) %>);
// some jquery code after alert
Let see the tutorial.
Create a new project for this tutorial:
rails new dynamic_js_tutorial
- Generate "js" controller, with following command on directory of your rails project:
rails generate controller js script1 script2 script3
This command produces the following output:
route get "js/script3"
route get "js/script2"
route get "js/script1"
Rename *.html.erb files to *.js on js views directory:
mv app/views/js/script1.html.erb app/views/js/script1.js
mv app/views/js/script2.html.erb app/views/js/script2.js
mv app/views/js/script3.html.erb app/views/js/script3.js
You should modify app/controllers/js_controller.rb file:
class JsController < ApplicationController
before_filter :js_content_type # set HTTP header information
@dynamic_message = "hello" # modified
alert('<%= @dynamic_message %>');
Include script1.js in your layout file (app/views/layouts/application.html.erb):
<%= stylesheet_link_tag :all %>
<%= csrf_meta_tag %>
<%= yield %>
We have to generate a HTML test page, what we can request.
Generate this page with this command:
rails generate controller home index
This command produce the following output:
route get "home/index"
As you see the home_controller.rb and index.html.erb files created.
Now you can try out the code in action.
Start rails server with
rails servercommand and visit this URL: http://localhost:3000/home/index
Now you can write dynamically generated JavaScipt files in Ruby on Rails. You may use it on real your projects.