Using Value Object as an ActiveRecord Attribute
Two weeks ago, I was working on a simple task, to add a query param to an embed url. This embed is actually from the main site, which I'm also working on occasionally. I understands how this urls work and which path of a url lead to which resource. And while my task was just to add a query param, I had to add it in 2 different classes. Which of course, as a good software engineer, I think that at least something must be refactored.
The problem was in attempts to validate the embed url, these classes uses almost similar but slightly different method. One of them only needs to validate a livestreaming url, and the other needs to validate both livestreaming and vod urls. In my first few attempts, I wrote a couple of validator classes, and I even tried to use ActiveSupport::Concern to wrap the validators. But something keep telling me, "Hey, this doesn't feel right, but that one doesn't either". "Yea, okay. But what will feel right?" Yes, you read the title correctly.
Finally, it came up to me that this is the job for the Value Object guy from that Domain Design Development village. Enough said, this embed url should be a Value Object. Thus, could be validated with its own validation methods. My solution was initially something like this:
class EmbedUrl attr_reader :url def initialize(https) @url = https end def valid? # insert code here end def livestream? # insert code here end def vod? # insert code here end end
Sorry, to be continued ...
Comments
Post a Comment