Allows us to use Value Objects for things that are part of our models.
Ok, so I just learned that ActiveRecord has a composed_of
method which allows you to more easily manage value objects that belong to ActiveRecord models. This could be really helpful for apps as they get more complex.
Value Objects are objects that describe things. They represent elements of a design where we only care about what they are, not who they are. Frequent examples are things like Temperature, Color, Points, Addresses - parts of a thing that make more sense as a conceptual whole.
As Eric Evans’ seminal Domain-Driven Design puts it:
The attributes that make up a Value Object should form a conceptual whole. E.g. Street, city and post code shouldn’t be separate attributes of a Person object, they are part of a single, whole Address.
Without Address Value Object:
Person:
id
name
street
city
postcode
With Address Value Object:
Person:
id
name
address
Address:
street
city
state
The benefits here are that once you have an Address
, you can ask questions of it, rather than if you just had a collection of fields. e.g. Address#in_county?(:middlesex)
.
The legends of OO (Fowler, Evans), and Ruby (Metz, Bernhardt) all praise the power of Value Objects to just make life easier.
Right now, if I wanted to add an Address
value object to another model, we’d have to make it ourselves:
def address
Address.new(street: street_address, city:, state:, zipcode:)
end
But with composed_of
, we can do this:
class Person < ApplicationRecord
composed_of :address, mapping: { street_address: :street, city:, zipcode:, state:}
end
The way in is good - means in both directions we can forget more about the columns in our database and more about the meaning of the data in our application.
— Adam Dawkins
Who are Dragon Drop?
Dragon Drop is a specialist web and app development agency. The team has extensive full-stack technical credentials and a strong focus on user experience.
The Dragon Drop founding team have over 40 years of web development and project experience. They have managed or developed over 100 significant ecommerce and web projects during their careers, including implementations for major UK high street retailers, financial services companies and government agencies.
Their approach to innovative solutions stems from perspectives gained as retailer, software supplier and web agency.