Skip to content
Sagie Maoz edited this page Jul 8, 2017 · 12 revisions

:watch => false

How-to watch and renew variables


:camel_case => false

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)

:camel_depth => :recursive or :camel_depth => my_int

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);

:namespace => 'newNamespace'

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)

:init => true

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

:need_type => true

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>

:need_tag => true

To pull json without script tag (kudos to @afa):

<head>
  <title>some title</title>
  <script><%= include_gon(:need_tag => false) %></script>
  ...

Result:

window.gon=...

:nonce => "foo"

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>