Let me first say that I welcome the efforts of this issue. It will be difficult for you to find someone who is more interested in developing software in the right way - including using small methods that do one thing at the same level of abstraction than I do.
However, I must say that on this I actually object to the premise of the question. I think your as_json best as it is.
Most importantly, this is the decoupling of customers from implementations. The only thing Car#as_json clients should know is that the return value is a JSON representation for Car . And as_json does it and does it well. Caching and / or fetching is a part of the implementation that must remain inside the method, and it is a part that is an integral part of this one task.
Saying differently would be if any method with an if was "wrong" because it does two things. Of course, this is not so. In both cases (using if and using Rails.cache.fetch ), the implementation of the method is some atomic action, the result of which is based on the condition.
This is one thing that can go in one of two ways, which is not the same as two things.
Meanwhile, I would have to disagree with @severin's answer. Of course, this will work, but now you have connected your opinion with the implementation details. Nothing, and, of course, your opinion, should have any idea of โโthe caching method or even that caching is involved. In my opinion, you have already skipped abstraction with this approach. Maybe it doesnโt matter, but since we are talking about the โright wayโ to do something ...
So, I say, keep things as they are. But I think this is a big question.
Vidya
source share