Files
sure/app/models/time_series.rb
Jose Farias fc3ade392a Refactor TimeSeries artifacts (#651)
* Reindent TimeSeries classes

* Fix spacing in time series tests

* Remove trend tests where current is nil

I think if we've gotten this far with a nil value for current, there's a data integrity problem.

If we allow this, we'll have to be very defensive in our code. Best to raise and fix early.

* Reindent Money class

* Refactor TimeSeries artifacts

* Use as_json in TimeSeries

* Bring back tests for trends where current is nil

* Bring back trend test

* Correctly enumerate trend test

* Use favorable_direction for trend_styles helper

* Make trend public in TimeSeries::Value

* Allow nil current values in trends

I think I might've gotten it wrong before, nils might appear in trends if values are unavailable for snapshots

* Clean up TimeSeries::Trend

* Skip trend values same class validations if any values are nil

* Refactor Money

* Remove object parsing in TimeSeries::Value

We're only every passing hashes
2024-04-22 08:30:42 -04:00

58 lines
1.2 KiB
Ruby

class TimeSeries
DIRECTIONS = %w[ up down ].freeze
attr_reader :values, :favorable_direction
def self.from_collection(collection, value_method)
collection.map do |obj|
{
date: obj.date,
value: obj.public_send(value_method),
original: obj
}
end.then { |data| new(data) }
end
def initialize(data, favorable_direction: "up")
@favorable_direction = (favorable_direction.presence_in(DIRECTIONS) || "up").inquiry
@values = initialize_values data
end
def first
values.first
end
def last
values.last
end
def on(date)
values.find { |v| v.date == date }
end
def trend
TimeSeries::Trend.new \
current: last&.value,
previous: first&.value,
series: self
end
# `as_json` returns the data shape used by D3 charts
def as_json
{
values: values.map(&:as_json),
trend: trend.as_json,
favorable_direction: favorable_direction
}.as_json
end
private
def initialize_values(data)
[ nil, *data ].each_cons(2).map do |previous, current|
TimeSeries::Value.new **current,
previous_value: previous.try(:[], :value),
series: self
end
end
end