Good information and well-written! At one of my companies, I picked up the pattern of making a class for constants within their namespace, and referring to the array of them as ALL. Example:
Never thought about using a separate module to keep them grouped but it is a really good technique.
I topically use this in a way in which the constants end up being almost private.
I either wrap the value checks in small predicate methods:
defred?color==COLORS_REDend
Or if I need them with active record I create scopes like the ones in the post.
Even in tests I try to avoid using them for setup and if I have factory_bot at hand I create traits for the different values instead.
This way you end up with code which is a bit more decoupled from this specific implementation detail and when your constant is not enough and you need to build an object instead you'll save a lot of grepping and seddingπ
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Good information and well-written! At one of my companies, I picked up the pattern of making a class for constants within their namespace, and referring to the array of them as
ALL
. Example:This was especially helpful as more and more categories of constants became part of the codebase
There's some good enum style tricks on this page! Thanks to both of you for sharing.
Thanks to you for reading!
Never thought about using a separate module to keep them grouped but it is a really good technique.
I topically use this in a way in which the constants end up being almost private.
I either wrap the value checks in small predicate methods:
Or if I need them with active record I create scopes like the ones in the post.
Even in tests I try to avoid using them for setup and if I have factory_bot at hand I create traits for the different values instead.
This way you end up with code which is a bit more decoupled from this specific implementation detail and when your constant is not enough and you need to build an object instead you'll save a lot of
grep
ping andsed
dingπ