Introducing Concerns
What are Concerns?
Concerns are just modules which allow us to group similar behaviours in one place.
Concerns in controller specifically can be used to share code between controller and also extracting similar behaviours (eg. concerns for SSO, authentication etc.) from controllers for future re-use or for greater clarity and modularity.
Where are Concerns located?
How do you write a concern?
It's pretty simple to write a concern
- Create a module under 'concerns' folder
- extend the module with ' ActiveSupport::Concern'
- Define all the methods which you need to group
- include the concern inside your controller, all the methods will be accessible as instance methods now
Example (RequestServiceLoader)
java_import com.bibliocommons.v2.service.request.RequestServicer
module RequestServiceLoader
extend ActiveSupport::Concern
# Allowing to read the request service instead of an instance method
attr_reader :request_service
def load_services
setup_request_service
load_global_service
end
def setup_request_service
@request_service = RequestServicer.new()
@request_service.enter_request_scope(request.remote_ip, cookies[:agency_id], cookies[:session_id] || params[:session_id], cookies[:language],cookies[:current_scope_id])
end
.....
end
Example - Adding it to ApplicationController
class ApplicationController < ActionController::Base
# We include the module here
include RequestServiceLoader
# Now we can call the methods directly of RequestServiceLoader
before_filter :load_services
def some_method
# We are using method instead of instance method
user = request_service.authService.get_logged_in_
end
end
obfuscation or common concern?
One thing we can also do in concerns is call filters eg.
module RequestServiceLoader
extend ActiveSupport::Concern
included do
before_filter :load_services
after_filter :end_request
end
def load_services
..
end
def end_request
...
end
end
These filters will be added as soon as you include the module so they may run before your application filters. I think we should avoid it for greater clarity and control.
Introducing Concerns
By amunda
Introducing Concerns
- 21