Class: ObjectView::HighChartLoadJavascriptAjax

Inherits:
Javascript show all
Defined in:
lib/object_view/high_chart_ajax_javascript.rb

Instance Attribute Summary

Attributes inherited from Element

#acceptable_children, #children, #single_line, #tag

Instance Method Summary collapse

Methods inherited from Element

#<<, #add, #add_with_tag, #attr, #attributes, #css_class=, #find_element_with_tag, #id=, #is_acceptable_child?, #on_click=, #render, #render_attributes, #render_children, #style, #style=

Constructor Details

#initialize(chart_data_list, prepend_script) ⇒ HighChartLoadJavascriptAjax

Returns a new instance of HighChartLoadJavascriptAjax.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/object_view/high_chart_ajax_javascript.rb', line 6

def initialize(chart_data_list, prepend_script)
  super()
  
  script = ""
  if (prepend_script != nil)
    script += prepend_script
  end
  
  script += chart_class_script()
  
  
  script += "
      _chartHash = new Object();
      _chartList = new Array();
   "
  chart_data_list.each do |chart_data|
    params_line = params_for_chart(chart_data)
    refresh_seconds = chart_data.ajax_refresh_seconds 
    if (refresh_seconds == nil)
      refresh_seconds = "null"
    end
    
    #   'apple=green&extent=' + _extent + ''
    #   'extent=' + _extent + '&' + 'apple=green' + '&' + 'banana=yellow'
    script += "    
        #{params_line}
     var chartDraw = new HighChartDraw('#{chart_data.id}', '#{chart_data.ajax_url}', params, #{refresh_seconds});
     _chartHash['#{chart_data.id}'] = chartDraw;
     _chartList.push(chartDraw);
     console.log('_chartList.length: ' + _chartList.length);
       "         
  end
  script += "
      function periodicCheckForChartDraw() {
        var chartCount = _chartList.length;
        //console.log('periodicCheckForChartDraw()  count: ' + chartCount);
        for (i = 0; i < chartCount; i++) {
          chart = _chartList[i];
          chart.periodicCheck();
        }
      }
    	setInterval(periodicCheckForChartDraw, 500);
  "
  
  self.add script
end

Instance Method Details

#chart_class_scriptObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/object_view/high_chart_ajax_javascript.rb', line 53

def chart_class_script
  script = 
  "
  
  function prepareChartData(chartData) {
    console.log('Data type: ' + typeof(chartData));
    prepareObjectAndChildren(chartData);
  }
  
  
  
  function prepareObjectAndChildren(object) {
    if (typeof(object) == 'object') {
      for (var key in object) {
          if (object.hasOwnProperty(key)) {
              //console.log('key is: ' + key + ', value is: ' + object[key]);
              child = object[key];
              if (typeof(child) == \"object\" ) {
                prepareObjectAndChildren(child);
              } else if (typeof(child) == 'string') {
                //console.log('STRING key is: ' + key + ', value is: ' + object[key]);
                if (child.indexOf('/@') == 0) {
                  var functionCode = child.replace('/@', '');
                  functionCode = functionCode.replace('@/', '');
                  object[key] = function() {
                        return eval(functionCode);
                    }
                  //console.log('STRING (functionCode): ' + key + ', value is: ' + functionCode);
                  //console.log('STRING was function ' + key + ', value is: ' + object[key]);
                }
              }
          }
      }
    }
  }
  //response = response.replace('\"@@', '');
  //response = response.replace('@@\"', '');
  
  
  function HighChartDraw(chartId, ajaxUrl, ajaxParams, refreshSeconds) {
    console.log('Created HighChartDraw  (' + chartId + ')');
  	this.nextTimeToDraw = 0;
    this.currentlyDrawing = false;
  	this.ajaxUrl = ajaxUrl;
  	this.ajaxParams = ajaxParams;
  	this.refreshSeconds = refreshSeconds;
  	this.chartId = chartId;
    console.log('Initializing chart: ' + this.chartId);
  	this.chartRequestMade = false;
  	this.clearChart();
  }
 
  HighChartDraw.prototype.buildParamString = function() {
    var paramString = '';
    for (var paramName in this.ajaxParams) {
        if (this.ajaxParams.hasOwnProperty(paramName)) {
          paramValue = this.ajaxParams[paramName];
          if (paramString.length > 0) {
            paramString = paramString + '&';
          }
          paramString += paramName + '=';
          var indexOfVal = paramValue.indexOf('VAR|');
          if (indexOfVal == 0) {
            var variable = paramValue.substring(4, paramValue.length);
            console.log('Variable for eval: ' + variable);
            paramString += encodeURIComponent(eval(variable));
            //paramString += eval(variable);
          } else {
            paramString += encodeURIComponent(paramValue);
            //paramString += paramValue;
          }
        }
    }
    console.log('Post params: ' + paramString);
    return paramString;      
  }


  HighChartDraw.prototype.draw = function() {
      try {
          this.currentlyDrawing = true;
          console.log('Drawing chart (' + this.chartId + ')');
          var chartElementId = 'chart_1';
  	    	var chartId = this.chartId;
          $.ajax({
              type: 'GET',
              url: this.ajaxUrl,
              data: this.buildParamString(),
              dataType: 'text',
              success: function(response) {
                var chartData = jQuery.parseJSON(response);
                prepareChartData(chartData);
                $('#' + chartId).highcharts(chartData);
              },
              error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#' + chartId).html('<h3>Error getting chart data - QA server may be down.</h3>');
              }
          });
          console.log('finished drawing chart.  Queuing another drawHighChart request.');
          if (this.refreshSeconds != null) {
            this.makeChartDrawRequest(1000 * this.refreshSeconds);
          }
          this.currentlyDrawing = false;
      } catch(error) {
         console.log('Exception drawing chart: ' + error);
         this.currentlyDrawing = false;
         this.makeChartDrawRequest(1000);
         throw error;
      }
      this.currentlyDrawing = false;
  }

  HighChartDraw.prototype.clearChart = function() {
  	$('#' + this.chartId).html('<h2 style=\"color: #aaaaaa\">Building Chart...</h2>'); 
  }

  HighChartDraw.prototype.makeChartDrawRequest = function(millisFromNow) {
      var nextTime = jQuery.now() + millisFromNow;
      if ((this.nextTimeToDraw == null) || (nextTime < this.nextTimeToDraw)) {
        this.nextTimeToDraw = nextTime;
      }
      console.log('Request to drawHighChart (' + this.chartId + ') queued for: ' + this.nextTimeToDraw);
  }

  HighChartDraw.prototype.periodicCheck = function() {
    //console.log('periodicCheck for ' + this.chartId);
  	var now = jQuery.now();
  	if (this.nextTimeToDraw != null) {
  	  if (now > this.nextTimeToDraw) {
  	    this.doingPeriodicCheck = false;
  	    if (this.currentlyDrawing == false) {
  	      this.nextTimeToDraw = null;
  	      this.draw();
  	    } else {
          //console.log('periodicCheck for ' + this.chartId + '  currently drawing, so ignoring request');
  	    }
  	  } else {
        //console.log('periodicCheck for ' + this.chartId + '  next draw time not reached');
      }
  	} else {
        //console.log('periodicCheck for ' + this.chartId + '  nextTimeToDraw is null');
    }
  	this.doingPeriodicCheck = false;
  }
  "
  return script
end

#chart_data_load_script(chart_data_list) ⇒ Object

def params_for_chart(chart_data)

params_str = "var params = '' + "

chart_data.ajax_params.each do |name, value|
#  params_string += "#{name}=#{value}&"
  if (value.to_s.start_with? "VAR|")
    params_str += "'#{name}=' + #{value[4..(value.length - 1)]}"
  else
    encoded_value = URI.encode_www_form([[name, value]])
    params_str += "'#{encoded_value}'"
    #params_str += "'#{name}=#{encoded_value}'"
  end
  params_str += "+'&'+"
end

params_str = params_str[0..params_str.length - 6]
params_str += ';'
# if (params_string.length > 0)
#   params_string = params_string[0..params_string.length - 2]
# end
# params_string = URI.encode_www_form(params)
return params_str

end



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/object_view/high_chart_ajax_javascript.rb', line 320

def chart_data_load_script(chart_data_list)
  script = ""
 	chart_data_list.each do |chart_data|  
    
  
    script += 
    "
              var chartElementId = '#{chart_data.id}';
              $.ajax({
                type: 'GET',
                url: '#{chart_data.ajax_url}',
                data: params,
                dataType: 'text',
                success: function(response) {
                  //alert('Response: ' + response);
                  var chartData = jQuery.parseJSON(response);
                  //alert('Response: ' + response);
                  $('#' + chartElementId).highcharts(chartData);"
                  
    
    if (chart_data.ajax_refresh_seconds != nil)                    
      script += "              
                  makeChartDrawRequest(#{chart_data.ajax_refresh_seconds * 1000});
          "        
    end
                  
    script += "
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                  $('#' + chartElementId).html('<h3>Error getting chart data - QA server may be down.</h3>');
                }
              });
    "
   end
   return script    
end

#clear_script_for_each_chart(chart_data_list) ⇒ Object



240
241
242
243
244
245
246
247
# File 'lib/object_view/high_chart_ajax_javascript.rb', line 240

def clear_script_for_each_chart(chart_data_list) 
  script = ""
 	chart_data_list.each do |chart_data|  
    chart_data.id
    script += "  $('##{chart_data.id}').html('<h3 style=\"color: #aaaaaa\">Building Chart</h3>');\n"
  end
  return script
end

#draw_chart_function(ajax_refresh_seconds, chart_data_list) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/object_view/high_chart_ajax_javascript.rb', line 203

def draw_chart_function(ajax_refresh_seconds, chart_data_list)
  script = "
    function drawHighChart() {
        console.log('drawHighChart called');
    "
    script += "
        try {
            _currentlyDrawing = true;
            console.log('Drawing charts.');
            //alert('drawHighChart()');
            "
  script +=  "     #{chart_data_load_script(chart_data_list)}\n" 
  
  if (ajax_refresh_seconds != nil)   
    script += "     
             console.log('finished drawing chart.  Queuing another drawHighChart request.');
             makeChartDrawRequest(#{ajax_refresh_seconds * 1000});\n
             _currentlyDrawing = false;
    "
  end
    
  script += "    
        }  catch(error) {
           console.log('Exception drawing chart: ' + error);
           _currentlyDrawing = false;
           makeChartDrawRequest(1000);
        }
        "
        
  script +=   "
        _currentlyDrawing = false;
      }
   "
   return script
end

#params_for_chart(chart_data) ⇒ Object



286
287
288
289
290
291
292
293
294
# File 'lib/object_view/high_chart_ajax_javascript.rb', line 286

def params_for_chart(chart_data)
  params_str = "var params = new Object();\n"

  chart_data.ajax_params.each do |name, value|
      params_str += "     params['#{name}'] = '#{value}';\n"
  end
  
  return params_str
end

#periodic_check_function(chart_data_list) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/object_view/high_chart_ajax_javascript.rb', line 249

def periodic_check_function(chart_data_list)
  script = "
  function periodicCheck(chartId) {
      var now = jQuery.now();
      if (_nextTimeToDraw[chartId] != null) {
        if (now > _nextTimeToDraw[chartId]) {
          _doingPeriodicCheck = false;
          if (_currentlyDrawing == false) {
            _nextTimeToDraw[chartId] = null;
            drawHighChart(chartId);
          } else {
          }
        }
      }
      _doingPeriodicCheck = false;
    }
  }
  "
  
  script += 
  "
  function periodicCheckAll() {
    if (!_doingPeriodicCheck) {
      _doingPeriodicCheck = true;
      "
      
  chart_data_list.each do |chart_data|
    script += "   periodicCheck('#{chart_data.id}'); "
  end    
      
  script +=    
      "
    }
  }
  "
end