Two superpowers to mix in
In lesson 45, Comparable gave a parcel six comparisons – now the two most famous mixins go to work for timelog. Comparable: as soon as your class can <=> (the “spaceship operator”: -1, 0 or 1), the mixin gives you <, >, ==, between? and more.
At the same time, meet Data – Ruby's class for immutable value objects:
Duration = Data.define(:minutes) do
include Comparable
def <=>(other)
minutes <=> other.minutes
end
def to_s
"#{minutes / 60}h #{minutes % 60}min"
end
end
breaks = [Duration.new(minutes: 90), Duration.new(minutes: 45), Duration.new(minutes: 120)]
breaks.max.to_sData.define creates a class with fixed fields, equality and inspect for free – and the objects are frozen (no accidental mutation, see lesson 110). So whoever needs a different value doesn't change the object but asks with for a new one:
short = Duration.new(minutes: 30)
long = short.with(minutes: 90)
[short.to_s, long.to_s, short.frozen?, short == Duration.new(minutes: 30)]Two Data objects with the same content are equal (==) – which makes them a good fit for values such as a duration, an amount of money or a period of time. For mutable cases there's the older Struct.
The second superpower: Enumerable. Your class provides just each – and receives the ENTIRE collection toolbox in return: map, select, sum, sort_by, group_by … exactly the methods from lesson 105, now on your own class.
Timesheet enumerable: include Enumerable plus an each method that forwards the block to @entries.each. Then the last line works.class Timesheet
# include ...
def initialize(entries)
@entries = entries
end
# def each(&block)
# ...
# end
end
ts = Timesheet.new([
{ project: "A", hours: 2.0 },
{ project: "B", hours: 1.0 }
])
# ts.sum { |e| e[:hours] }