Values
Summary
Values is a tiny library for creating value objects in ruby.
Classes created using Value mostly look like classes created using
Struct or
OpenStruct,
but fix two problems with those:
Struct and OpenStruct constructors can take fewer than the default number of arguments and set other fields as nil:
Point = Struct.new(:x, :y)
Point.new(1)
p = OpenStruct.new(x: 1)
p.y
Struct and OpenStruct objects are mutable:
p = Point.new(1, 2)
p.x = 2
p.x
p = OpenStruct.new(x: 1, y: 2)
p.x = 2
p.x
Values is Better
Values fixes both of the above problems.
Constructors require expected arguments:
Point = Value.new(:x, :y)
Point.new(1)
Instances are immutable:
p = Point.new(1, 2)
p.x = 1
Features
Values also provides an alternative constructor which takes a hash:
p = Point.with(x: 3, y: 4)
p.x
Values can copy and replace fields using a hash:
p = Point.with(x: 1, y: -1)
q = p.with(y: 2)
Value classes can be converted to a hash, like OpenStruct:
Point.with(x: 1, y: -1).to_h
Values also supports customization of value classes inheriting from Value.new
:
class Point < Value.new(:x, :y)
def to_s
"<Point at (#{x}, #{y})>"
end
end
p = Point.new(1, 2)
p.to_s
Values does NOT have all the features of Struct or OpenStruct (nor is it meant to).