Class: Datum

Inherits:
Data show all
Defined in:
lib/everythingrb/datum.rb

Overview

An immutable, dot-notation object built from attributes in a single call

Think of it as the sealed counterpart to OpenStruct: the ergonomics of OpenStruct.new(hash) with the immutability of Data. Values are stored as-is (nested hashes and arrays are left untouched), so the object is immutable only at the top level. Use Hash#to_datum when you want the conversion to recurse.

Examples:

Build an object inline

config = Datum.new(host: "localhost", port: 3000)
config.host # => "localhost"

Nested data is left as-is

data = Datum.new(name: "Bob", meta: {role: "admin"})
data.meta # => {role: "admin"} (still a Hash)

Structural equality

Datum.new(a: 1) == Datum.new(a: 1) # => true

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Everythingrb::InspectQuotable

#in_quotes

Class Method Details

.new(attributes = {}) ⇒ Datum

Builds an immutable object from the given attributes

Examples:

Datum.new(host: "localhost", port: 3000)

Parameters:

  • attributes (Hash) (defaults to: {})

    The members and their values for the new object

Returns:

  • (Datum)

    An object whose members match the given keys



32
33
34
# File 'lib/everythingrb/datum.rb', line 32

def self.new(attributes = {})
  define(*attributes.keys.map(&:to_sym)).new(*attributes.values)
end

Instance Method Details

#==(other) ⇒ Boolean Also known as: eql?

Compares against another Datum by attributes rather than by class

Every Datum is backed by its own anonymous Data class, so the default comparison (which requires an identical class) would never match. This compares the underlying attributes instead.

Parameters:

  • other (Object)

    The object to compare against

Returns:

  • (Boolean)

    True when other is a Datum with equal attributes



47
48
49
# File 'lib/everythingrb/datum.rb', line 47

def ==(other)
  other.is_a?(Datum) && to_h == other.to_h
end

#hashInteger

Returns a hash code derived from the attributes

Keeps #hash consistent with #eql? so equal Datums collapse to the same Hash key or Set member.

Returns:

  • (Integer)


61
62
63
# File 'lib/everythingrb/datum.rb', line 61

def hash
  to_h.hash
end