The latest LuckyCast covers using the decorator design pattern to simplify how you can present Time objects to users in your Crystal apps.
While the entirety of the screencast is within the context of a Lucky app, very little is Lucky-specific and is hopefully useful in a number of other contexts!
3 Likes
What do you see as a benefit of the decorator shard? I would just use a plain struct for this.
record TimeDecorator, time : Time do
forward_missing_to @time
def pretty_date
time.to_s("%Y-%-m-%D")
end
end
2 Likes
Completely agreed, @straight-shoota! In fact, the very next episode is going to be a walkthrough of implementing this without any dependencies at all.
In the future, I have plans to try to integrate this a bit more heavily with the views in Lucky so that every object you pass to a page will implicitly be “Decorated” without having to initialize them yourself, but you’re correct that right now the macro basically sets up exactly what you’ve proposed: decorator/base.cr at main · stephendolan/decorator · GitHub
I’ll also admit that since macros are new to me coming from Ruby, I was excited to find a relatively easy use case that allowed my code to be a bit more expressive and to get some experience with extracting common code into a shard.
Thanks very much for the comment, and for all of your work and contributions to this wonderful language .
1 Like
Thanks
You should probably consider using structs for decorators. That avoids heap allocations and should be a lot more efficient for this use case. A decorator typically doesn’t need to be mutable.
For automatic decoration there might be some issues to keep in mind, when view code expects a type but the actual value is just a wrapper. A wrapper responds to the same methods, but it can’t fool is_a?(Time)
=)
That’s great advice. I opened an issue on the shard repo to explore structs more, and will be sure to use structs in the next video where I show building these from scratch!
Thanks for the callouts regarding the view decoration… definitely something I hadn’t thought of, but it’ll be a fun challenge to explore! Who knows, if I get it working maybe I can even turn it into another LuckyCast