module ForestLiana class QueryStatGetter attr_accessor :record def initialize(params) @params = params end def perform if @params['record_id'] @params['query'].gsub!('?', @params['record_id'].to_s) end result = ActiveRecord::Base.connection.execute(@params['query']) case @params['type'] when 'Value' if result.count result_line = result.first if !result_line['value'] raise error_message(result_line, "'value'") else @record = Model::Stat.new(value: { countCurrent: result_line['value'], countPrevious: result_line['previous'] }) end end when 'Pie' if result.count result.each do |result_line| if !result_line['value'] || !result_line['key'] raise error_message(result_line, "'key', 'value'") end end @record = Model::Stat.new(value: result.to_a) end when 'Line' if result.count result.each do |result_line| if !result_line['value'] || !result_line['key'] raise error_message(result_line, "'key', 'value'") end end result_formatted = result.map do |result_line| { label: result_line['key'], values: { value: result_line['value'] }} end @record = Model::Stat.new(value: result_formatted) end end end private def error_message(result, key_names) "The result columns must be named #{key_names} instead of '#{result.keys.join("', '")}'" end end end