How do you create javascript functions that are available project-wide in Ruby on Rails?

ruby-on-rails, ruby-on-rails-3

Solution

Assuming you are using asset pipeline & coffeescript: Don't write code in application.js

In order to keep clean structure, create a folder (eg: `application`) in `app/assets/javascripts`

then require it in your `application.js`

//= require jquery
//= require jquery_ujs

//= require_tree ./application

Create a coffee file (eg: `app/assets/javascripts/application/my_feature.js.coffee`

@test = ->
  alert('Hello world')

Coffee output:

(function() {

  this.test = function() {
    return alert('Hello world');
  };

}).call(this);

It's preferable to use namespaces:

@myGreatFeature =
  test: ->
    alert('Hello world')

or according to the coffeescript FAQ, you could write

namespace = (target, name, block) ->
  [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3
  top    = target
  target = target[item] or= {} for item in name.split '.'
  block target, top

namespace 'myGreatFeature', (exports) ->
  exports.test = ->
    alert('Hello world')

then you can call `myGreatFeature.test()` everywhere

Problem

I put the following function in my application.js: ``` function test() { alert("See Me") } ``` classrooms/_new_small.html.haml: ``` :javascript alert('test'); test(); ``` In my application.html.haml I'm using the following: ``` = javascript_include_tag 'application' ``` I'm getting a `test is not defined` error in my firebug console. Isn't the test function supposed to be available project-wide because its in the application.js file? Thanks edit: I'm rendering the page via javascript. Would that affect it? ``` $('#test_container').html("<%= escape_javascript(render :partial => 'classrooms/new_small') %>"); ```

Original source

Related problems