I think it's best to do the following, but please comment if there is a better way.
module ValueObjectable
def initialize(args)
super(args)
freeze
end
end
class Location < Struct.new(:country, :city, keyword_init: true)
include ValueObjectable
end
##Feature##
# 1.Can be initialized with Hash like OpenStruct
tokyo = Location.new(country: 'Japan', city: 'Tokyo')
=> #<struct Location country="Japan", city="Tokyo">
# 2.You don't have to define the comparison logic yourself
fukuoka = Location.new(country: 'Japan', city: 'Fukuoka')
tokyo == fukuoka
=> false
# 3.Value is unchanged
tokyo.country = 'U.S'
FrozenError: can't modify frozen Location
Recommended Posts