DEV Community

Augusts Bautra
Augusts Bautra

Posted on • Edited on

How I use Rails' `concerning` macro

Turns out Rails models have a neat macro - concerning. It allows defining an inline concern.

Docs: https://api.rubyonrails.org/classes/Module/Concerning.html

Discussion

On the one hand, it's convenient for grouping methods, and have that grouping exist in an actual code structure, not just come comment block, and it's helpful to have that grouping live in the same file.
On the other hand, unfortunately, the separation of the concern from the model is so weak as to be nonexistent - nothing stops us from calling model methods in the concern module, leading to the popular flaw of secret API. And it's unclear how to spec the concern in isolation, we really need a separate file for that.

Conclusion

I'll use concerning exclusively for grouping methods that will never be refactored out of the model, to identify sub-groups of behavior within a model, for example a Document model having two sub-functionalities - one regarding versioning/revisions and the other regarding the underlying file (size, type, etc.), and spec them in the model spec, but in a dedicated describe block

describe Document do 
  describe "#some_method" do
  end

  describe described_class::Revisions do
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
pimp_my_ruby profile image
Pimp My Ruby

Hi, thanks for sharing this!