Passing dynamic ruby variables into a .js.erb file


#1

Hi,

I’m hoping someone could please assist with this problem.

I’ve
got a scenario where I use these dynamic variables within a template
.dashboard.js.erb file (using it to construct a grafana dashboard):

#dashboard.js.erb

/* global _ */

‘use strict’;

var windows, document, $, jQuery, moment, kbn, ARGS;
var dashboard;
var rows = 5;
var env = <%= metric %>;
var nodes_env = <%= node %>;

and my recipe uses the following resource:-

#recipe.rb

dashboard_path = "/usr/share/public/grafana"
file = "dashboard.js"
metric = "blue-monolith"
node = “nodes.production_blue”

template File.join(dashboard_path, file) do
source "dashboard.js.erb"
variables({
:metric => metric,
:node => node
})
end
end

I’ve tried the following inside my .js.erb file:-
var env = <%= metric %>;
var env = ‘<%= metric %>’;
var env = <%= metric.to_json %>;

All of which result in error at the end of a chef run:-
Chef::Mixin::Template::TemplateError (undefined local variable or method `metric’ for #Chef::Mixin::Template::TemplateContext:0x00000005f49ed0)

Does anyone know how to represent these dynamic variables (metric and node) in a .js.erb file?

Many thanks


#2

Hi Angela,

You are passing in a Ruby symbol so try

var env = <%= @metric %>;

OR

var env = <%= @:metric %>;


#3

Hi Chris,

Thanks you very much! That worked.