Class: ChartingUi::ChartersController

Inherits:
ApplicationController show all
Defined in:
app/controllers/charting_ui/charters_controller.rb

Instance Method Summary collapse

Instance Method Details

#fetch_dataObject



5
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'app/controllers/charting_ui/charters_controller.rb', line 5

def fetch_data
	model = charter_params[:model_name].classify.constantize
	if model == nil then
		respond_to do |format|
			format.json { render :json => { :error => "#{t("charting_ui.Wrong_model")}: '#{model}'"}, :status => 422 }
		end
		return
	end

	key = JSON.parse(charter_params[:model_key])
	if model.charting_ui_available_methods == nil
		respond_to do |format|
			format.json { render :json => { :error => "#{t('charting_ui.Need_to_define_acts_as_chartable')}: '#{key}'"}, :status => 422 }
		end
		return
	end
	key.each do |k|
		if ! model.charting_ui_available_methods.include?(k)
			respond_to do |format|
				format.json { render :json => { :error => "#{t('charting_ui.Wrong_key')}: '#{k}'"}, :status => 422 }
			end
			return
		end
	end

	global_result = {}
	model.all.each do |item|
		key.each do |k|
			begin
				key_result = item.send(k)
				if is_date? key_result
					key_result = modify_date(key_result, charter_params[:date_scope])
				else
					key_result = { value: key_result, display: key_result }
				end

				global_result = create_new_block(key_result, global_result, key)

				global_result[key_result[:value]][:values][k][:value] += 1
				global_result[key_result[:value]][:values][k][:ids].push(item.id)
				global_result[key_result[:value]][:ids].push(item.id)
			rescue Exception => e
				respond_to do |format|
					format.json { render :json => { :error => "#{t('charting_ui.Unknow_key')}: '#{key}' | Error: #{e}"}, :status => 422 }
				end
				return
			end
		end
	end

	global_result.delete(2) if global_result.has_key? 2

	all_integer = true
	global_result.each{|k,v| all_integer = false unless k.is_a? Integer}

	if all_integer
		tmp = global_result.map{|k,v| v[:key]}
		min_value = tmp.min
		max_value = tmp.max
		min_value.upto(max_value) {|n| create_new_block({value:n , display: n}, global_result, key)}
	end

	global_result = global_result.map{|k, v| v }
	global_result.each { |item| item[:values] = item[:values].map{|k,v| v} }
	global_result = global_result.sort { |left, right| left[:key] <=> right[:key] }

	respond_to do |format|
		format.json { render :json => { :success => global_result}, :status => 200 }
	end
	return
end