Skip to content

[outdated] Gerando gráficos com o Lazy HighCharts

guiocavalcanti edited this page Nov 7, 2011 · 1 revision

##HighCharts

Os relatórios gráficos do Redu são gerados através da biblioteca de JavaScript HighCharts. Em poucas palavras, basta criar o objeto HighChart através do inicializador HighChart.chart().

Um exemplo de gráfico seria:

  $(document).ready(function() {
      chart1 = new Highcharts.Chart({
         chart: {
            renderTo: 'chart-container-1',
            defaultSeriesType: 'bar'
         },
         title: {
            text: 'Fruit Consumption'
         },
         xAxis: {
            categories: ['Apples', 'Bananas', 'Oranges']
         },
         yAxis: {
            title: {
               text: 'Fruit eaten'
            }
         },
         series: [{
            name: 'Jane',
            data: [1, 0, 4]
         }, {
            name: 'John',
            data: [5, 7, 3]
         }]
      });
   });

Mais informações sobre as opções aceitas pelo HighCharts pode ser encontrada na documentação oficial

Lazy HighCharts

O plugin do Rails Lazy HighCharts tem como objetivo gerar o código JavaScript responsável pela criação do objeto HighChart. Com isso temos algumas vantagens como

  1. Todo o código pode ser escrito no controller e model.
  2. Quase não há necessidade de conversão de dados (Ruby ~> JavaScript)
  3. A geração de gráficos via requisições assíncronas se torna mais simples.

Um exemplo de Lazy HighChart pode ser visto abaixo:

  @engagement_x_time = HighChart.new do |f|
      f.title(:text => "Participação em #{first.strftime("%B de %Y")}")
      f.chart(:defaultSeriesType => 'line')
      f.y_axis(:title => { :text => 'Participação' }, :min => 0)
      f.x_axis(:title => { :text => "Dias do mês" },
               :type => 'datetime')
      f.series(:name => 'Tópicos',
               :pointInterval => 24 * 3600 * 1000,
               :pointStart => first.to_time.to_i * 1000,
               :data => topics)
      f.series(:name => 'Atividades no Mural',
               :pointInterval => 24 * 3600 * 1000,
               :pointStart => first.to_time.to_i * 1000,
               :data => statuses)
   end

Para exibir o gráfico na view é necessário incluir a biblioteca JS do HighCharts e renderizar o JavaScript gerado através do helper <%= high_chart() %>. Por exemplo:

<%= javascript_include_tag "highcharts" %>
  <div class="panel squeeze">
    <%= high_chart("post-x-spaces", @h)  %>
  </div>

Mais informações podem ser encontradas na wiki do Lazy HighCharts