Helping devs understand concerns faster

IMO, the problem with concerns, is that they are really nothing special, they are just plain Ruby modules. But the fact that a new word was introduced creates an expectation that you’re missing something. Which is something I totally understand.

A concern is a module that you extract to split the implementation of a class or module in coherent chunks, instead of having one big class body. The API surface is the same one, they just help organize the code. A concern is a regular Ruby mixin, there’s nothing else, it is not a new concept. It is plain Ruby.

So, when you extract pricing-related API from a Hotel class, you typically do something like this:

# app/models/hotel.rb
class Hotel
  include Pricing
end

# app/models/hotel/pricing.rb
module Hotel::Pricing
  # Hotel pricing-related logic.
end

There, Hotel::Pricing is a concern. But that idiom is not Rails-specific, this is vanilla Ruby programming.

Directories like app/models/concerns are meant for mixins that can be reused, in this case, in the model layer.

On the other hand, AS::Concern is orthogonal. A concern is a Ruby module used in a certain way (vs used as a namespace, say). Ruby has the included callback that gets fired when a module is included somewhere, and you receive the enclosing class or module as argument, that allows you to decorate it, for example. Well, the included DSL macro is essentially the same thing, except that the decoration looks prettier. It is a DSL for mixins that want to decorate their enclosing classes or modules.

But, perhaps surprisingly, a mixin does not need to extend AS::Concern to be a concern. Or to call concerning. A concern is a Ruby module with a certain purpose, as explained above, and whether you use those DSLs or not is irrelevant.

And you see the problem, concerns are so simple that they do not deserve a full guide. Concerns are mixins, if you are a Ruby programmer, you already know what a mixin is and their use case to modularize APIs.

But at the same time, a post like this is needed to explain that they are just that!

That means there is something to address here, I believe we are missing a definition, but don’t know exactly how to fix it.

6 Likes