Crafting Immutable Value Objects in Ruby: The Modern Approach
In Ruby, creating value objects is an effective way to manage related data with immutability and clarity.
The Data class, introduced in Ruby 3.2, provides a modern, idiomatic approach to defining simple, immutable objects comparable by type and value. This ensures data consistency and ease of management throughout your codebase.
Defining a Value Object
To define a value object using the Data class, consider an object representing an amount with a value and currency:
Amount = Data.define(:value, :currency)
amount = Amount.new(value: 100, currency: 'USD')
This object is immutable, meaning its attributes cannot be changed once set, and it is comparable by type and value.
Adding Custom Methods
You can enhance your value objects by adding custom methods. For instance, to convert the amount to a different currency:
Amount = Data.define(:value, :currency) do
def convert_to(new_currency, rate)
Amount.new(value: value * rate, currency: new_currency)
end
end
Benefits of Using Value Objects
1. Immutability: Ensures data integrity as objects cannot be altered once created.
2. Clarity: Group related data under a meaningful name, making your code more readable.
3. Flexibility: Allows adding utility methods and computed properties.
You can create robust and maintainable Ruby applications by leveraging the Data class.
👉 I published a full deep dive on this topic at https://allaboutcoding.ghinda.com/how-to-create-value-objects-in-ruby-the-idiomatic-way