Class: ChartCandy::Builder::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/chart-candy/builder/base.rb

Direct Known Subclasses

Counter, Donut, Line

Instance Method Summary collapse

Constructor Details

#initialize(id, options = {}) ⇒ Base

Returns a new instance of Base.



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/chart-candy/builder/base.rb', line 2

def initialize(id, options={})
  options.reverse_merge! from: nil, to: nil, step: nil

  @from = options[:from] ? Time.parse(options[:from]) : nil
  @to = options[:to] ? Time.parse(options[:to]) : Time.now

  @chart = { id: id }
  @chart[:step] = options[:step] if options[:step]
  @chart[:title] = t('title')

  # Subtitles are likely to be dynamic and thus cannot be defined in translation files.
  @chart[:subtitle] = options[:subtitle].presence

  @chart[:period] = ChartCandy::Builder.period(@from, @to, step: @chart[:step]) if @from
end

Instance Method Details

#close_chartObject



18
19
20
# File 'lib/chart-candy/builder/base.rb', line 18

def close_chart
  # Hooks before closing a chart
end

#filenameObject



22
23
24
25
26
27
28
# File 'lib/chart-candy/builder/base.rb', line 22

def filename
  name = [title.parameterize]
  name << @from.strftime('%Y%m%d') if @from
  name << @to.strftime('%Y%m%d') if @to
  name = name.compact.join('-')
  "#{name}.xls"
end

#idObject



30
31
32
# File 'lib/chart-candy/builder/base.rb', line 30

def id
  @chart[:id]
end

#l(date, options = {}) ⇒ Object



34
35
36
37
38
# File 'lib/chart-candy/builder/base.rb', line 34

def l(date, options={})
  options.reverse_merge!(format: :date_long)

  return ChartCandy.localize(date, options)
end

#periodObject



40
41
42
# File 'lib/chart-candy/builder/base.rb', line 40

def period
  @chart[:period]
end

#set_period_from_data(data) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/chart-candy/builder/base.rb', line 44

def set_period_from_data(data)
  @from = data.first
  @to = data.last

  @chart[:step] = ChartCandy::Builder.get_step_from_interval(data[1] - data[0]) if not @chart[:step]

  @chart[:period] = ChartCandy::Builder.period @from, @to, step: @chart[:step]
end

#t(path, vars = {}) ⇒ Object



53
54
55
56
57
# File 'lib/chart-candy/builder/base.rb', line 53

def t(path, vars={})
  vars.reverse_merge! :default => ''

  ChartCandy.translate("#{id.gsub('-', '_')}.#{path}", vars)
end

#titleObject



59
60
61
# File 'lib/chart-candy/builder/base.rb', line 59

def title
  @chart[:title]
end

#to_jsonObject



63
64
65
66
67
# File 'lib/chart-candy/builder/base.rb', line 63

def to_json
  close_chart

  return @chart.to_json
end

#to_xlsObject



69
70
71
72
73
# File 'lib/chart-candy/builder/base.rb', line 69

def to_xls
  close_chart

  return ChartCandy::Builder::XlsBuilder.chart_to_xls @chart
end