Using the Rails googlecharts gem on HTTPS / SSL

I use gogle googlecharts in my rails application for some simple graphs. It works beautifully, except that my application is required for SSL encryption at any time. In order to pull out Google charts, the gem chart, of course, makes an HTTP request for google, which leads to a warning to the browser about some insecure content on the page for most users. Has anyone else encountered this problem and developed a solution to avoid a warning? I'm afraid I will need to figure out a way to make an http call, save the google image returned locally, and then display this in the application, but thought someone else had found a good way to handle this.

+3
source share
4 answers

The endpoint of the Google Chart API API is stored in a class variable @@urlinside the Gchart class. So initially I was thinking about monkeypatching a class variable to set the url to https

# Put this in an initializer
Gchart.send :class_variable_set, :@@url, "https://chart.apis.google.com/chart?"

Alas, Google Charts does not work through https. Therefore, we cannot use this method. Since the methods of the Gchart class simply return the URL, we can wrap the calls in the proxy controller method that the API call server performs and proxy it to the client using the send_data ActionController method using your selection protocol. This way you don't have to reinvent the wheel of the Gchart library.

class ChartsController < ApplicationController
  require 'net/http'
  require 'gchart'

  def show
    options = params.except :controller, :action
    options[:data].map! { |x| x.to_i } if options[:data]
    begin 
      chart = URI.parse(Gchart.send options.delete(:type), options)
      send_data Net::HTTP.get(chart), :content_type => 'image/png', :disposition  => 'inline'
    rescue
      raise ActiveRecord::RecordNotFound
    end
  end

end

A helper that you can use in your views:

module ApplicationHelper

  def chart_tag(options ={})
    image_tag chart_path(options)
  end

end

and route

map.resource :chart, :only => :show

Using:

<%= chart_tag :type => "line", :size => '200x300', :title => "example title", :bg => 'efefef', :legend => ['first data set label', 'second data set label'], :data => [10, 30, 120, 45, 72] %>

, .

+4

GchartRB gem, . to_escaped_url URI.parse .

+1

, , . , HTTP, ( )

:

require 'net/http'
def googlechart
  send_data Net::HTTP.get("http://chart.apis.google.com/chart?#{params[:api]}"),
    :content_type => 'image/png',
    :disposition  => 'inline'
end

:

<%= image_tag googlechart_path(:api=>'cht=p&chd=s:Uf9a&chs=200x100&chl=January') %>

, .

0

Source: https://habr.com/ru/post/1724716/


All Articles