Running Ruby in the browser via script type=”text/ruby” Russell Beattie is back with Mowser
Apr 17

rjs command line to generate JavaScript from Ruby

Tech Add comments

Since I want to write Ruby and generate JavaScript, why not use RJS?

To get going, I wanted to take just the pieces that do the RJS work in Rails and use them to just do the JS emitting.

I ended up with a script that takes a file and emits the JS from it:

#!/usr/bin/env ruby
# -----------------------------------------------------------------------------
# rjs - go through an RJS file and output the JavaScript
# -----------------------------------------------------------------------------
require 'rubygems'
gem 'actionpack'

require 'action_controller'

include ActionView::Helpers::JavaScriptHelper
include ActionView::Helpers::PrototypeHelper
include ActionView::Helpers::ScriptaculousHelper

def get_code; ARGV.first; end

# -----------------------------------------------------------------------------
#  Main
# -----------------------------------------------------------------------------
raise 'rjs: must pass in an RJS file to load' unless ARGV.size > 0

code = get_code

output = ''

eval <<-EoC
output = update_page do |page|

puts output

E.g. with a sample test.rjs of

page.insert_html :bottom, 'list', "
  • item name
  • " page.visual_effect :highlight, 'list' page.hide 'status-indicator', 'cancel-link'

    I would run % rjs test.rjs and would get:

    new Insertion.Bottom("list", "
  • item name
  • "); new Effect.Highlight("list",{}); ["status-indicator", "cancel-link"].each(Element.hide);

    I want to extract what is needed here, put it in jruby.jar, and then use RJS as the basis for the generation. It would be nice if RJS wasn't quite so tightly coupled into Rails. Then the fun of:

    <script type="text/ruby">'#items li').each do |value|

    would be a reality.

    NOTE: I have to give a huge kudos to the JRuby team for something. I was using an ancient jruby-complete.jar for the initial implementation of ruby int he browser. I didn't want to do something newer as I didn't want to build JRuby from scratch. Half the time getting an open source project to build is a very painful and time wasting experience.

    With JRuby I grabbed the project from Subversion, ran ant, and it freaking worked first time. I am quite amazed. Now, ruby in the browser is running on JRuby head.

    2 Responses to “rjs command line to generate JavaScript from Ruby”

    1. replicahandbags Says:

      thanks for sharing

    2. replica handbags Says:

      thank you again!

    Leave a Reply

    Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

    Q: What is the number before 3? (just put in the digit)