0

I have a problems with javascripts assets in Ruby on Rails. Descripttion: I have two files in app/assets/javascript folder.

  1. "constans.js" include a constant array "var FEATURES = new Array["A","B","C"]"
  2. "route.js.erb" <%= FEATURES[1] %>

Now , I'm implementing my function in "route.js.erb" but I can't access the "FEATURES" array ?
I searched on Google but can't not find the solution.
So, anybody can help me? Thanks! ( my first question in stack overflow , sorry for my bad english)

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
zatcsc
  • 21
  • 5

2 Answers2

1

use

window.FEATURES = new Array["A","B","C"]"

in constants.js

and make sure that the constants.js is being loaded.

Norly Canarias
  • 1,736
  • 1
  • 21
  • 19
0

There are several important factors:

  1. Scoping of the variable
  2. Calling the variable in ERB

Scope

First, you need to ensure your variable is scoped globally. To do this, you've declared the variable in constants.js, so you need to ensure this is called before the routes.js.erb file. You should also take @user3243476's advice & append it to the window object:

#js/constants.js
window.FEATURES = new Array["A","B","C"]

ERB

Secondly, you're calling routes.js.erb (which is fine), but inside you're calling <%= FEATURES["1"] %>. Problem. This is calling a Rails constant, not the JS one. This means even if your variable's scope is global, you're trying to call one which doesn't exist.

You'll need to do this:

#js/routes.js.erb
alert(FEATURES["1"]);
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • Thanks for your answer. The problem is that I can't not call Js constant in Rails tag . So I got another way to solve my problem already. – zatcsc May 08 '14 at 11:19