Skip to content

Commit 0bc017c

Browse files
committed
First steps to watch functionality
1 parent b8527fa commit 0bc017c

File tree

3 files changed

+50
-2
lines changed

3 files changed

+50
-2
lines changed

lib/gon.rb

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
require 'action_controller'
66
require 'gon/base'
77
require 'gon/global'
8+
require 'gon/watch'
89
require 'gon/request'
910
require 'gon/helpers'
1011
require 'gon/escaper'
@@ -22,6 +23,10 @@ def global
2223
Gon::Global
2324
end
2425

26+
def watch
27+
Gon::Watch
28+
end
29+
2530
def method_missing(method, *args, &block)
2631
if ( method.to_s =~ /=$/ )
2732
if public_method_name? method
@@ -65,7 +70,12 @@ def get_variable(name)
6570
end
6671

6772
def set_variable(name, value)
68-
Request.gon[name] = value
73+
if Gon::Watch.need_return?
74+
Gon::Watch.clear
75+
Gon::Watch.return_variable(value)
76+
else
77+
Request.gon[name] = value
78+
end
6979
end
7080

7181
def store_builder_data(builder, data, options)

lib/gon/base.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def render_data(options)
2424
script.html_safe
2525
end
2626

27-
def get_controller(options)
27+
def get_controller(options = {})
2828
options[:controller] ||
2929
Gon::Request.env['action_controller.instance'] ||
3030
Gon::Request.env['action_controller.rescue.response'].

lib/gon/watch.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
module Gon
2+
class Watch
3+
class << self
4+
5+
def method_missing(method, *args, &block)
6+
@return = return_variable?(method)
7+
Gon.send method, *args, &block
8+
end
9+
10+
def clear
11+
@return = false
12+
end
13+
14+
def need_return?
15+
defined?(@return) and @return
16+
end
17+
18+
def return_variable(value)
19+
controller = Gon::Base.get_controller
20+
21+
controller.render :json => value
22+
end
23+
24+
private
25+
26+
def return_variable?(variable)
27+
controller = Gon::Base.get_controller
28+
params = controller.params
29+
variable = variable.to_s.gsub('=', '')
30+
31+
controller.request.xhr? &&
32+
params[:gon_return_variable] &&
33+
params[:gon_watched_variable] == variable
34+
end
35+
36+
end
37+
end
38+
end

0 commit comments

Comments
 (0)