如果現在用rails開一個新專案
你會在model與controller裡面發現一個空的資料夾叫做「concerns」
這就是rails預設你會用來放concern的地方
concern簡單說就是可以將model與controller相同的部分抽出
成為一個更高階的方法,避免重複
實踐「DRY」的精神
但一般而言新手可能會更熟悉將controller整理到service或是上層controller
例如說有一段controller如下:
class WebsiteController < ApplicationController
def index
@events = Event.all
end
end
用service整理如下:
#app/services/event_service.rb
class EventService
def self.source
Event.all
end
end
class WebsiteController < ApplicationController
def index
@events = EventService.source
# 將複雜的邏輯藏到service裡面
end
end
用上層controller整理如下:
#上層的controller
class BaseController < ApplicationController
def source
Event.all
end
end
class WebsiteController < BaseController
def index
@events = source
# 將複雜的邏輯藏到BaseController裡面
end
end
但如果要整理model,選擇似乎就少了些
這時候concern就是個好選擇
class Company < ApplicationRecord
scope :open, -> { where(statue: "open")}
def is_open?
status == "open"
end
end
class Event < ApplicationRecord
scope :open, -> { where(statue: "open")}
def is_open?
status == "open"
end
end
像是上面的例子,可能在專案內會有類似的scope,instance method
可以抽出來:
#app/models/concerns/can_openable.rb
module CanOpenable
extend ActiveSupport::Concern
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
scope :open, -> { where(statue: "open")}
end
end
module InstanceMethods
def is_open?
status == "open"
end
end
end
class Company < ApplicationRecord
include CanOpenable
end
class Event < ApplicationRecord
include CanOpenable
end
如此就可以達到整理重複程式碼的效果
參考文件與參考文件2
API