Skip to content

Commit a21d7b9

Browse files
committed
Merge pull request gazay#47 from torbjon/master
Added :init option for initializing window.gon variable on each request
2 parents 725e14d + c6001b6 commit a21d7b9

File tree

4 files changed

+35
-7
lines changed

4 files changed

+35
-7
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,16 @@ You can change the namespace of the variables:
8282
...
8383
```
8484

85+
You can initialize window.gon = {}; on each request
86+
87+
``` erb
88+
<head>
89+
<title>some title</title>
90+
<%= include_gon(:init => true) %>
91+
<!-- include your action js code with 'serverExports' namespace -->
92+
...
93+
```
94+
8595
You can get json without script tag (kudos to @afa):
8696

8797
``` erb

lib/gon/base.rb

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@ def render_data(options)
1212
start = "#{need_tag ? '<script>' : ''}window.#{namespace} = {};"
1313
script = ''
1414

15-
if options[:camel_case]
16-
data.each do |key, val|
17-
script << "#{namespace}.#{key.to_s.camelize(:lower)}=#{val.to_json};"
18-
end
19-
else
20-
data.each do |key, val|
21-
script << "#{namespace}.#{key.to_s}=#{val.to_json};"
15+
if data.present?
16+
if options[:camel_case]
17+
data.each do |key, val|
18+
script << "#{namespace}.#{key.to_s.camelize(:lower)}=#{val.to_json};"
19+
end
20+
else
21+
data.each do |key, val|
22+
script << "#{namespace}.#{key.to_s}=#{val.to_json};"
23+
end
2224
end
2325
end
2426

lib/gon/helpers.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ def include_gon(options = {})
1313
elsif Gon.global.all_variables.present?
1414
Gon.clear
1515
Gon::Base.render_data(options)
16+
elsif options[:init].present?
17+
Gon.clear if Gon.all_variables.present?
18+
Gon::Base.render_data(options)
1619
else
1720
""
1821
end

spec/gon/basic_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,19 @@
7979
'gon.int=1;'
8080
end
8181

82+
83+
it 'outputs correct js without variables, without tag and gon init' do
84+
@base.include_gon(need_tag: false, init: true).should == \
85+
'window.gon = {};'
86+
end
87+
88+
it 'outputs correct js without variables, without tag and gon init' do
89+
Gon.int = 1
90+
@base.include_gon(need_tag: false, init: true).should == \
91+
'window.gon = {};' +
92+
'gon.int=1;'
93+
end
94+
8295
end
8396

8497
it 'returns exception if try to set public method as variable' do

0 commit comments

Comments
 (0)