class Chartd::Chart

Constants

ERR_BAD_DATASET
ERR_TOO_MANY_DATASETS

Attributes

dataset[R]
max[RW]

allow min and max to be changed after instantiating a Chart

min[RW]

allow min and max to be changed after instantiating a Chart

Public Class Methods

new(dataset = [], min: nil, max: nil, ylabels: true, options: {}) click to toggle source
# File lib/chartd/chart.rb, line 16
def initialize(dataset = [], min: nil, max: nil, ylabels: true, options: {})
  raise ERR_BAD_DATASET unless dataset.is_a?(Array)

  # Check if dataset is multidimensional and if so, use it as is.
  # Otherwise make it multidimensional.
  if dataset[0].is_a?(Array)
    raise ERR_TOO_MANY_DATASETS if dataset.count > 5
    @dataset = dataset
  else
    @dataset = [dataset]
  end

  # calculate min and max across the entire dataset but only if they are
  # not set explicitly.
  @min = min || dataset.flatten.min
  @max = max || dataset.flatten.max

  @ylabels = ylabels

  @options = default_options.merge(options)
end

Public Instance Methods

url() click to toggle source
# File lib/chartd/chart.rb, line 38
def url
  u = BASE_URL.dup

  # encode each piece of data and append it to URL as params
  encoded_data = @dataset.each_with_index.map do |d, i|
    ["d#{i}", Encoder.encode(d, min: @min, max: @max)]
  end

  # set labels for y axis when they’re enabled (which they are by default)
  if @ylabels
    @options[:ymin] ||= @min
    @options[:ymax] ||= @max
  end

  u.query = URI.encode_www_form(
    @options.merge(encoded_data.to_h)
  )
  u.to_s.force_encoding('utf-8')
end

Private Instance Methods

default_options() click to toggle source

Default options for a chart URL, can be overridden when instantiating a Chart using the options argument.

# File lib/chartd/chart.rb, line 62
def default_options
  { w: 580, h: 180 }
end