Concern là module được include vào nhiều class để tái sử dụng logic.
Rails cung cấp ActiveSupport::Concern để tránh boilerplate.
ruby
# app/controllers/concerns/authenticatable.rb
module Authenticatable
extend ActiveSupport::Concern
included do
before_action :require_login
end
def require_login
redirect_to login_path unless current_user
end
end
class PostsController < ApplicationController
include Authenticatable
endModel Concern hoạt động tương tự — thường dùng để share scope, callback, hay helper method giữa nhiều model.
Concern tốt cho logic dùng ở nhiều nơi, nhưng không nên lạm dụng để "giấu" logic phức tạp.
A Concern is a module included in multiple classes to share logic.
Rails provides ActiveSupport::Concern to reduce boilerplate.
ruby
# app/controllers/concerns/authenticatable.rb
module Authenticatable
extend ActiveSupport::Concern
included do
before_action :require_login
end
def require_login
redirect_to login_path unless current_user
end
end
class PostsController < ApplicationController
include Authenticatable
endModel Concerns work the same way — commonly used to share scopes, callbacks, or helper methods across models.
Concerns are useful for logic shared in many places, but shouldn't be overused to "hide" complex logic.