Calculates directional trend from current and previous values, returning color-coded indicators, percentage changes, and JSON-serialized data for time-series visualization.
class TimeSeries::Trend
include ActiveModel::Validations
attr_reader :current, :previous, :favorable_direction
validate :values_must_be_of_same_type, :values_must_be_of_known_type
def initialize(current:, previous:, series: nil, favorable_direction: nil)
@current = current
@previous = previous
@series = series
@favorable_direction = get_favorable_direction(favorable_direction)
validate!
end
def direction
if previous.nil? || current == previous
"flat"
elsif current && current > previous
"up"
else
"down"
end.inquiry
end
def color
case direction
when "up"
favorable_direction.down? ? red_hex : green_hex
when "down"
favorable_direction.down? ? green_hex : red_hex
else
gray_hex
end
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key