11class Gon
2- class Watch
2+ class Watch < Gon
33 class << self
44
5+ JS_FUNCTION = \
6+ "window.gon.watch = function(name, possibleOptions, possibleCallback) {
7+ var callback, key, options, value, xhr, _ref;
8+ if (typeof $ === 'undefined' || $ === null) {
9+ return;
10+ }
11+ if (typeof possibleOptions === 'object') {
12+ options = {};
13+ _ref = gon.watchedVariables[name];
14+ for (key in _ref) {
15+ value = _ref[key];
16+ options[key] = value;
17+ }
18+ for (key in possibleOptions) {
19+ value = possibleOptions[key];
20+ options[key] = value;
21+ }
22+ callback = possibleCallback;
23+ } else {
24+ options = gon.watchedVariables[name];
25+ callback = possibleOptions;
26+ }
27+ xhr = $.ajax({
28+ type: options.type || 'GET',
29+ url: options.url,
30+ data: {
31+ _method: options.method,
32+ gon_return_variable: true,
33+ gon_watched_variable: name
34+ }
35+ });
36+ xhr.done(callback);
37+ return true;
38+ };"
39+
40+ def render
41+ JS_FUNCTION + "window.gon.watchedVariables=#{ all_variables . to_json } ;"
42+ end
43+
544 def all_variables
645 @watch_variables || { }
746 end
@@ -10,27 +49,31 @@ def clear
1049 @watch_variables = { }
1150 end
1251
13- def need_return?
14- defined? ( @return ) and @return
15- end
16-
1752 def return_variable ( value )
1853 controller = Gon ::Base . get_controller
1954
20- controller . render :json => value
55+ controller . render :text => value . to_json
2156 end
2257
2358 private
2459
25- def method_missing ( method , *args , &block )
26- if return_variable? ( method )
27- Gon . send method , *args , &block
60+ def set_variable ( name , value )
61+ if return_variable? ( name )
62+ return_variable value
63+ else
64+ variable = { }
65+ @watch_variables ||= { }
66+ env = Gon ::Request . env
67+ variable [ 'url' ] = env [ 'ORIGINAL_FULLPATH' ]
68+ variable [ 'method' ] = env [ 'REQUEST_METHOD' ]
69+ variable [ 'name' ] = name
70+
71+ @watch_variables [ name ] = variable
72+ super
2873 end
2974 end
3075
3176 def return_variable? ( variable )
32- return false if variable !~ /=$/
33-
3477 controller = Gon ::Base . get_controller
3578 params = controller . params
3679 variable = variable . to_s . gsub ( '=' , '' )
0 commit comments