Created
August 4, 2016 20:02
-
-
Save luctus/cd958210fff73b57b2ddb1b5ae8ac854 to your computer and use it in GitHub Desktop.
Ruby module that generates a static jpg chart using the HighCharts servers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ChartStatificator | |
extend ActiveSupport::Concern | |
# need test | |
def generate_static_chart | |
Rails.logger.debug ">>> static_chart for #{id} <<<" | |
data = { | |
'options': {series: chart.series_data, | |
title: chart.options[:title], | |
yAxis: {title: {text: nil}, labels:{}}, | |
xAxis: {categories: chart.options[:xAxis][:categories], | |
labels: {step: chart.options[:xAxis][:labels][:step]}}, | |
plotOptions: chart.options[:plotOptions] | |
}, | |
'type': 'image/png', | |
'async': true | |
} | |
data[:options] = data[:options].to_json | |
@static_chart = upload_chart(chart_export_file(data)) | |
end | |
private | |
def chart_export_file(data) | |
require "net/http" | |
require "uri" | |
require 'open-uri' | |
highcharts_export = nil | |
x = Net::HTTP.post_form(URI.parse('http://export.highcharts.com'), data) | |
Rails.logger.debug ">>> #{x.body} <<<<" | |
retries = 1 | |
begin | |
highcharts_export = open("http://export.highcharts.com/#{x.body}") | |
raise 'hightcharts export no content' if highcharts_export.meta['content-length'].to_i == 0 | |
rescue => ex | |
retries += 1 | |
Rails.logger.debug ">>> Exception: #{ex.inspect} <<<" | |
if retries <= 5 | |
Rails.logger.debug ">>> Retrying in 2 seconds... take #{retries} <<<" | |
sleep(2) | |
retry | |
else | |
raise 'hichcharts export failed after all retries' | |
end | |
else | |
Rails.logger.debug ">>> Successfully read <<<" | |
end | |
highcharts_export | |
end | |
def upload_chart(file) | |
bucket = FOG_CONNECTION.directories.new(:key => ENV['AWS_BUCKET']) | |
chart_in_s3 = bucket.files.create( | |
key: "report-#{report.id}-widget-#{id}-#{title.parameterize}-#{Time.now.strftime("%Y%m%d%H%M%S")}.png", | |
body: file.read, | |
public: true | |
) | |
Rails.logger.info ">>> #{chart_in_s3.public_url} <<<" | |
chart_in_s3.public_url.gsub('https://s3.amazonaws.com/', 'http://') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@luctus what does ruby lint say about using single and double quotes?