Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
72 lines (51 sloc) 2.39 KB


This rails plugin will hide the messiness of passing variables from rails into javascript. It will automatically add the js needed to create a variable you define in rails, or add variables to objects.


Requires Json (require ‘json’)

./script/plugin install git://


in your controller:

jsvars[:loginPath] = login_path

  • Will create a global variable in the JS window object named ‘loginPath’ with the value you assigned.
jsvars[:myObject] = {:title => "My Page", :email => ""}
  • Adds the object variables that can be used as myObject.title & in the view javascipt.
  • This will add the object “myObject” if it does not exist, if it already does, only the variables will be added to the already existing object.
jsvars['myObj.myMeth.myValue'] = "myVar"
  • Adds the objects myObj, myMeth, myValue if they do not exist and defines the value of myObj.myMeth.myValue to myVar.
  • Only undefined objects will be added, so if myObj exists but myMeth and myVal do not, they will be added to the myObj object.

Example of extending an object:
In controller:

jsvars[:login] = {:path => '/login'}

in view:
    var login = {
        loginFuntion: function () {
            // ....
        specialVar: "My special Var"    

in JS:

login.loginFunction = function()
    login.specialVar = 'My special Var'
    login.path = '/login'

Getting the rails environment in javascript for all pages
In ApplicationController:

before_filter :set_js_env

def set_js_env jsvars[:railsEnv] = RAILS_ENV end


railsEnv = "development"

What this solves

This solves the mess of stuff like this:

    var loginPath = '<%= login_path %>';

(requiring the js to be left in an .html.erb file, or a .js.erb file)

to simple adding:

jsvars[:loginPath] = login_path

to the controller and allowing all js to be kept in .js files out of the html.
This can get especially messy with objects with a few rails defines attributes.


Copyright © 2010 Erick Schmitt, released under the MIT license.

Something went wrong with that request. Please try again.