Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access the yml file from application.js in rails?

I have a yml file and i need the keys to be used in the application.js file in the scripts. I cannot able to access it from the script. Please help me. I have the following lines in the initializer

APP_CONFIG = YAML.load_file("#{Rails.root}/config/filename.yml")[Rails.env]

and i have the following keys in my yml file

development:
  key1: 782364764527225794828437
  key2: sdjfbjs7e834284383984729
  key3: 73465365egfrf36462874727

and i access the keys in application.js file as

APP_CONFIG['key1']

but it seems to take nothing. But when i print the same thing in the view body as

<%= APP_CONFIG['key1'] %>

then it returns the value of the key1.

What should i do to access the value in application.js file. It also not works in the script body in the view itself.

like image 483
logesh Avatar asked Nov 29 '25 19:11

logesh


2 Answers

You cannot execute ruby command in a Javascript file

You need to figure out some other way to load the values in application.js

Like initialize them in app/views/layouts/application.html.erb as a global variable

<script>
  var key = '<%= APP_CONFIG['key1'] %>';
</script>

and use it in any Javscript file

 window.onload=function(){ alert(key);};
like image 198
Siva Avatar answered Dec 02 '25 08:12

Siva


You can not directly access your yml file content from JS file. What you can do is on your view page assign these keys to a js variable then it will be available to you for JS work

<script>
  var appConfigKeys = “<%= j APP_CONFIG.to_json.html_safe %>”;
  console.log(appConfigKeys);
</script>

If you want it to be available in other JS file as then you need to take help of global varibales.

<script>
  appConfigKeys = “<%= j APP_CONFIG.to_json.html_safe %>”;
  console.log(appConfigKeys);
</script>

Above solution will give you all the keys as a javascript hash If you need only first key, you can assign single key to a JS variable.

<script>
  appConfigKey = “<%= APP_CONFIG['key1'] %>”;
  console.log(appConfigKey);
</script>
like image 44
Kalpesh Fulpagare Avatar answered Dec 02 '25 09:12

Kalpesh Fulpagare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!