Composition class in Ruby: where to put, how many methods?

85 views Asked by At

On my Rails backend, I want to reuse several methods in different model classes.

Google search points me towards Ruby composition.

I have two questions concerning good practice:

  1. How many methods can go into a composition class? From this article, the part "Composition to the Rescue", it sounds like composition should only have one (non-private) method. Is it correct, and why?

  2. Which folder does the composition class file go? I read that service object goes to the app/services folder and concerns go to app/models/concerns. Which folder should be used for composition?

I understand that these are not strict rules, and I have searched but cannot get answers. I would really like to know about good practice and your experience. Thank you!

1

There are 1 answers

3
spickermann On BEST ANSWER

When using composition, then you can add as many methods to a mixin or concern as you like.

I recommend only combining methods into a mixin or concern when they have a common use-case. And there should be an obvious title or name for the group of methods. You could, for example, have a concern for methods related to logging or auditing, another of authentication or authorization related methods, and another for shared methods related to handling uploaded files.

The de facto standard for composition mixins in Ruby on Rails is using Concern and the default location for model concerns is app/models/concerns/... and app/controller/concerns/... for controller concerns.

See "Using Concerns" in the official Rails Guides and ActiveSupport::Concern in the Rails docs.