Rails lazy_high_charts: how to format tooltip label

150 views Asked by At

I would to print into my charts the hours and minutes, for example "development: 27 h 30 m".

Now I have this:

enter image description here

In my script "data" represents "hours"

{
  name: value.blank? ? "other" : value,
  data: all_weeks.merge(data_weeks.to_h).values.map do |data_value|
    data_value.nil? ? 0 : ( data_value.to_f / 60 ).round(2)
  end
}
....
f.tooltip(
   pointFormat: "<span style='color:{series.color}'>{series.name}</span>: <b>{point.y} h</b><br/>",
   split: true
)

I have tried to set point.y into pointFormat but no have effects. ( Edit: pointFormat would a generic string! )

How can I solve? Thanks in advance.

Edit:

I solved adding:

LazyHighCharts::HighChart.new("container") do |f|
  f.tooltip(
    formatter: "\
      function() { \
        var s = []; \
        s.push(this.x); \
        this.points.forEach(function(point) { \
          s.push('<b>' + point.series.name + '</b>: ' + Math.floor(point.y) + ' h ' + Math.floor((point.y % 1) * 60)  + ' m'); \
        }); \
        return s; \
      }".js_code,
    split: true
  )
  ....
end

enter image description here

2

There are 2 answers

0
Polo M2B On

Maybe you could introduce two variables, data_hours and data_minutes, and write a string interpolation with theses variables.

data_hours = data_value.to_i
data_minutes = ((data_value - data_hours) * 60).to_i
data_to_display = "#{data_hours} h #{data_minutes} m"

Hope it will help !

Written in 0.12 hours ;)

0
Aleksei Matiushkin On
["dev: 27.5 h", "dev: 22 h", "dev: 0.3h"].map do |s|
  s.gsub(/\d+(\.\d+)?\s*h/i) do |h|
    h, m = h.to_f.divmod(1)
    [
      ("#{h} h" unless h.zero?),
      ("#{(60 * m).round} m" unless m.zero?)
    ].compact.join(" ")
  end
end
#⇒ ["dev: 27 h 30 m", "dev: 22 h", "dev: 18 m"]