Class: Babl::Utils::Value
- Inherits:
-
Object
- Object
- Babl::Utils::Value
- Defined in:
- lib/babl/utils/value.rb
Overview
Construct deeply immutable value objects Similar to Struct, but:
-
Properties are assumed deeply immutable (#hash is assumed constant)
-
Constructor requires all arguments
-
#== has the same meaning as #eql?
Class Method Summary collapse
Class Method Details
.new(*fields) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/babl/utils/value.rb', line 12 def self.new(*fields) ::Class.new(::Struct.new(:_cached_hash, *fields)) do field_aliases = ::Array.new(fields.size) { |i| "v#{i}" } const_set(:FIELDS, fields.map(&:to_sym)) class_eval " def initialize(\#{field_aliases.join(',')})\n super(\#{['nil', field_aliases].join(',')})\n hash\n freeze\n end\n\n def hash\n self._cached_hash ||= super\n end\n\n def ==(other)\n eql?(other)\n end\n\n def self.with(hash = Utils::Hash::EMPTY)\n raise ::ArgumentError unless ::Hash === hash && (hash.keys - FIELDS).empty?\n new(*FIELDS.map { |f| hash.fetch(f) })\n end\n RUBY\n end\nend\n" |