lib/fnordmetric/widget.rb in fnordmetric-0.3.2 vs lib/fnordmetric/widget.rb in fnordmetric-0.5.0
- old
+ new
@@ -1,75 +1,80 @@
class FnordMetric::Widget
- attr_accessor :report
+ attr_accessor :gauges, :tick
- def initialize(options={})
- @options = options
- add_report(@options[:report]) if @options[:report]
+ def initialize(opts={})
+ @opts = opts
+
+ unless opts.has_key?(:title)
+ error! "widget can't be initialized without a title"
+ end
+
+ add_gauges(opts.delete(:gauges))
end
def title
- @options[:title]
+ @opts[:title]
end
- def metrics
- [@options[:metrics]].flatten.map{ |m|
- m.is_a?(FnordMetric::Metric) ? m : FnordMetric.metrics.fetch(m)
- }
+ def token
+ title.to_s.gsub(/[\W]/, '').downcase
end
- def tick
- @options[:tick] || 1.day
+ def add_gauges(gauges)
+ if gauges.blank? && has_tick?
+ error! "initializing a widget without gauges is void"
+ else
+ @gauges = gauges
+ end
+
+ if (ticks = gauges.map{ |g| g.tick }).uniq.length == 1
+ @tick = ticks.first
+ else
+ error! "you can't add gauges with different ticks to the same widget"
+ end
end
- def range
- @options[:range] || default_range
+ def error!(msg)
+ FnordMetric.error!(msg)
end
- def range_to_i
- (range.first.to_i..range.last.to_i)
+ def range
+ ensure_has_tick!
+ #@opts[:range] || default_range # FIXME: allow custom ranges, but assure that the range-start is 'on a tick'
+ default_range
end
def ticks
- range_to_i.step(tick.to_i).map{ |ts|
- (Time.at(ts)..Time.at(ts+tick.to_i))
- }.compact
+ ensure_has_tick!
+ range.step(@tick)
end
def default_range(now=Time.now)
- if tick.to_i == 1.day.to_i
- now = now+1.day
- te = Time.utc(now.year, now.month, now.day)
- (te-30.days)..(te-1.second)
- elsif tick.to_i == 1.hour.to_i
- te = Time.utc(now.year, now.month, now.day, now.hour)
- (te-24.hours)..(te-1.second)
- else
- (now-(tick*30))..now
- end
+ ensure_has_tick!
+ te = gauges.first.tick_at(now.to_i)
+ te += @tick if include_current?
+ rs = @tick == 1.hour.to_i ? 24 : 30
+ (te-(@tick*rs)..te)
end
-
- def add_report(report)
- @report = report
- end
+ def include_current?
+ !(@opts[:include_current] == false)
+ end
+
def data
- { :title => @options[:title] }
+ {
+ :title => @opts[:title],
+ :width => @opts[:width] || 100,
+ :klass => self.class.name.split("::").last
+ }
end
- def data_json
- data.to_json.gsub('"', '\'')
+ def render
+ data
end
- def include_current?
- !(@options[:current] == false)
- end
-
- def render(elem_id)
- %Q{
- <script type='text/javascript'>
- FnordMetric.render('#{elem_id}', #{data_json});
- </script>
- }
+ def ensure_has_tick!
+ error! "widget does not have_tick" unless has_tick?
end
end
\ No newline at end of file