1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-08-04 13:05:19 +02:00
Maybe/app/models/time_series/value.rb

62 lines
1.2 KiB
Ruby
Raw Normal View History

class TimeSeries::Value
2024-04-18 18:03:52 -06:00
include Comparable
2024-04-18 20:03:46 -06:00
include ActiveModel::Validations
2024-04-18 18:03:52 -06:00
attr_reader :value, :date, :original
2024-04-18 20:03:46 -06:00
validates :date, presence: true
validate :value_must_be_of_known_type
2024-04-18 20:03:46 -06:00
def initialize(obj, series: nil, previous: nil)
@date, @value, @original = parse_object obj
@series = series
@trend = create_trend previous
2024-04-18 20:03:46 -06:00
validate!
2024-04-18 18:03:52 -06:00
end
2024-04-18 18:03:52 -06:00
def <=>(other)
result = date <=> other.date
result = value <=> other.value if result == 0
result
end
2024-04-18 20:03:46 -06:00
def as_json
{
date: date,
value: value.as_json,
trend: trend.as_json
}
end
2024-04-18 18:03:52 -06:00
private
2024-04-18 20:03:46 -06:00
attr_reader :series, :trend
def parse_object(obj)
if obj.is_a?(Hash)
date = obj[:date]
value = obj[:value]
original = obj.fetch(:original, obj)
else
date = obj.date
value = obj.value
original = obj
end
[ date, value, original ]
end
def create_trend(previous)
TimeSeries::Trend.new \
current: value,
previous: previous&.value,
series: series
end
def value_must_be_of_known_type
unless value.is_a?(Money) || value.is_a?(Numeric)
errors.add :value, "must be a Money or Numeric"
end
2024-04-18 18:03:52 -06:00
end
end