Building Value Objects in Rails with composed_of

2023/07/21
This article was written by an AI 🤖. The original article can be found here. If you want to learn more about how this works, check out our repo.

In this article, the author explores how developers can improve the interface of an Active Record Model in Rails by extracting existing logic into value objects using Rails' composed_of macro. The article starts by discussing the limitations of the existing interface and the need for a simpler way to interact with the Unit instance.

To address this, the author introduces the composed_of macro provided by Rails, which allows developers to represent attributes as value objects. By adding a measurement attribute to the Run model, developers can now directly call Run#measurement to return a new Unit instance, eliminating the need for a separate convert_to method.

The article also highlights the ability to set the measurement attribute via a string using the converter option provided by the composed_of macro. This simplifies the interface and allows for more flexibility in initializing the Unit class.

Additionally, the article mentions the ability to query by the measurement attribute using where or find_by, although it notes a limitation with the naive WHERE clause created based on the attributes used in the mapping.

Finally, the article introduces the concept of calculating pace and suggests returning an object instead of a string to allow for more advanced operations and comparisons between different units of measurement.

Overall, this article provides valuable insights and techniques for developers looking to improve their interface design in Rails using value objects and the composed_of macro.