ClientVariable
exports your rails variables to client-side
Installation
Add this line to your application's Gemfile:
gem 'client_variable'
After you install and add it to your Gemfile, you need to run the generator:
rails g client_variable:install
It will create client_variable.yml in config folder, these variable in this file will be merged with variables defined through controller, exported to client-side
client_variable.yml
development:
app_name: <%= Rails.application.class.parent_name%>
production:
app_name: <%= Rails.application.class.parent_name%>
Usage
Add this line to app/views/layouts/application.html.erb
<head>
<title>some title</title>
<%= include_variable %>
<!-- include your action js code -->
...
Inspired from gon - https://github.com/gazay/gon, you can also do these in your controller
Write variables by(change each request)
client.variable_name = variable_value client.push({ :user_id => 1, :user_role => "admin" })
Or global You can use client.global for sending your data to js from anywhere! It's really great for some init data.
client.global.variable_name = variable_value
Add this line on top of app/assets/javascripts/application.js
//= require variable
I also define global variable in javascript rails
Access the varaibles from your JavaScript file:
rails.get('variable_name') // => variable_value
rails.get('user_id') // => 1
rails.set('a.b.c.d', '123') // rails.values => {a: {b: {c: {d: '123'}}}}
rails.get('a.b.c.d') // => '123'