Friday, March 07, 2025

Ruby Mixins as Rails Concerns

Ruby mixins are usually recommended to be used as 'traits', meaning having a name that is an adjective (e.g. `Archivable`) or descriptive of what the additional object trait is (e.g. `Importer`). That enables thinking naturally about what the class is by reading the mixin name.

I would avoid a common anti-pattern I have encountered in legacy code, which is the 'concern' naming approach of Rails concerns (e.g. `ArchivingConcern`) as that is not a correct use of mixins in Ruby. If an object 'contains' a concern, that comes across as a composition relationship not a form of inheritance like mixin inheritance, so it's confusing given that `include SomeMixin` makes the object behave as the mixin, not just include it in the sense of a composition relationship. We want to be able to think of the object class as being the mixin (e.g. `Archivable`); in other words, the mixin becomes a 'trait' of the object class.

It's amazing how cryptic, difficult to reason about, and expensive to maintain Ruby codebases become when they include countless 'concerns' without honoring the Ruby naming convention for mixins as representing "traits". 

I always like to double check all Software Engineering practices before accepting them in legacy codebases. 

No comments: