Helper vs Concern in Rails
Which one to use and why to use one in Rails
While writing some code the vital thing to consider is not to make anything complex by overloading a lot of stuff in one place. In Rails, the savior to such a situation could be a Helper/Concern/Service/Decorator and the list could go on. The basic idea is to split down the code into different places which can be used multiple times or to DRY the codebase and basically not to overload any model or controller with a lot of methods.
Since this blog is about Helpers and Concern, rather than wasting time let’s come to some common features between them. So basically, these are modules in which we can write any code and then add (include/extend) it to the controllers or models. After googling, the overall conclusion is that concerns are preferred for models/controllers and helpers for views.
The big question is if they both are modules then what makes them different?
Moreover, I have one more question: Why helpers are preferred for views and concerns for controllers and models?
So the answer is relatively simple because the concern uses inheritance from ActiveSupport::Concern
which provides numerous methods to a simple module. As we know, ActiveSupport
is responsible for providing extensions to the Ruby language and extra utilities. So basically, when compared with the simple module used in the Helper (or Service), the Concern has top-notch.
There are some features that we can utilize using ActiveSupport::Concern
which are listed below,
Include scopes and associations from the model
The ActiveSupport::Concern
provides a feature to add scopes as well as associations from the models as given below,
module Test
extend ActiveSupport::Concern
included do
scope :disabled, -> { where(disabled: true) }
end
end
Use of class methods
Similar to that, the ActiveSupport::Concern
provides one more feature to add class methods to the concerns (even if we include the concern module in any model) as given below,
module Test
extend ActiveSupport::Concern class_methods do
def print_value
puts "hello"
end
end
endclass Profile
include Test
...
end
There are a few more advantages of using ActiveSupport::Concern
as listed here.
So after looking at the advantages that the Concern seems to have, we can come to the conclusion that it is justified to prefer Concern for controllers and models whereas we can use helpers for the views (as views can have general methods to modify data).