Skip to content

Commit 1bb2a75

Browse files
committed
Changed storage from Rails.cache to OpenStruct constant, added specs
1 parent a44603b commit 1bb2a75

File tree

3 files changed

+45
-14
lines changed

3 files changed

+45
-14
lines changed

lib/gon.rb

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
11
require 'action_view'
22
require 'gon/helpers'
3+
require 'ostruct'
34

4-
module Gon
5-
def self.method_missing(m, *args, &block)
6-
gon_variables(m.to_s, args[0])
5+
Gon = OpenStruct.new
6+
7+
class << Gon
8+
def all_variables
9+
instance_variable_get :@table
710
end
8-
9-
def self.gon_variables(name=nil, value=nil)
10-
data = Rails.cache.read('gon_variables') || {}
11-
12-
new_data = {}
13-
new_data[name] = value if name && value
14-
15-
Rails.cache.delete('gon_variables')
16-
Rails.cache.write('gon_variables', (new_data.reverse_merge data))
11+
def clear
12+
instance_variable_set :@table, {}
1713
end
1814
end

lib/gon/helpers.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ def self.included base
66

77
module InstanceMethods
88
def include_gon
9-
data = Rails.cache.read('gon_variables') || {}
9+
data = Gon.all_variables || {}
1010

1111
script = "<script>window.Gon = {};"
1212
data.each do |key, val|
13-
script += "Gon." + key.to_s + val.to_json + ";"
13+
script += "Gon." + key.to_s + '=' + val.to_json + ";"
1414
end
1515
script += "</script>"
1616
script.html_safe

spec/gon/gon_spec.rb

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# gon_spec_rb
2+
require 'gon'
3+
4+
describe Gon, '#all_variables' do
5+
it 'returns all variables in hash' do
6+
Gon.a = 1
7+
Gon.b = 2
8+
Gon.c = Gon.a + Gon.b
9+
Gon.c.should == 3
10+
Gon.all_variables.should == {:a => 1, :b => 2, :c => 3}
11+
end
12+
13+
it 'supports all data types' do
14+
Gon.clear
15+
Gon.int = 1
16+
Gon.float = 1.1
17+
Gon.string = 'string'
18+
Gon.array = [ 1, 'string' ]
19+
Gon.hash = { :a => 1, :b => '2'}
20+
Gon.hash_w_array = { :a => [ 2, 3 ] }
21+
Gon.klass = OpenStruct.new
22+
23+
ActionView::Base.instance_methods.include?('include_gon').should == true
24+
base = ActionView::Base.new
25+
base.include_gon.should == "<script>window.Gon = {};" +
26+
"Gon.klass={\"table\":{}};" +
27+
"Gon.string=\"string\";" +
28+
"Gon.array=[1,\"string\"];" +
29+
"Gon.float=1.1;" +
30+
"Gon.int=1;" +
31+
"Gon.hash={\"a\":1,\"b\":\"2\"};" +
32+
"Gon.hash_w_array={\"a\":[2,3]};" +
33+
"</script>"
34+
end
35+
end

0 commit comments

Comments
 (0)