-
-
Notifications
You must be signed in to change notification settings - Fork 183
Options
Sagie Maoz edited this page Jul 8, 2017
·
12 revisions
How-to watch and renew variables
To camelize variables:
<head>
<title>some title</title>
<%= include_gon(:camel_case => true) %>
<!-- include your action js code with camelized variables -->
...
Result:
alert(gon.yourInt)
alert(gon.yourOtherInt)
alert(gon.yourArray)
alert(gon.yourHash)
To control depth of the camelizing:
<head>
<title>some title</title>
<%= include_gon(:camel_case => true, :camel_depth => 2) %>
...
Result:
alert(gon.testHash.testDepthOne.test_depth_two);
To change the namespace of variables:
<head>
<title>some title</title>
<%= include_gon(:namespace => 'serverExports') %>
<!-- include your action js code with 'serverExports' namespace -->
...
Result:
alert(serverExports.your_int)
alert(serverExports.your_other_int)
alert(serverExports.your_array)
alert(serverExports.your_hash)
To initialize window.gon = {}; on each request:
<head>
<title>some title</title>
<%= include_gon(:init => true) %>
...
Result: (presentness of gon object no longer must be checked)
window.gon // => {} if there was no data for current request
You can initialize script tag with type="text/javascript"
<head>
<title>some title</title>
<%= include_gon(:need_type => true) %>
<!-- include your action js code with 'serverExports' namespace -->
...
Result:
<script type="text/javascript">window.gon=...</script>
To pull json without script tag (kudos to @afa):
<head>
<title>some title</title>
<script><%= include_gon(:need_tag => false) %></script>
...
Result:
window.gon=...
To allow use with strict Content Security Policy (CSP) policies, a nonce can be provided. For example, to use with the secure_headers
gem (which also adds the correct CSP HTTP header to the response):
<head>
<title>some title</title>
<%= include_gon(:nonce => content_security_policy_script_nonce) %>
...
Result:
<script nonce="jV3upIrd0elFqLdQfULAD4WZpNflCR8hSbb1wpah14o=">window.gon=...</script>