Bạn từng viết concern chưa? Lợi ích của concern là gì?
Bạn từng viết concern chưa? Lợi ích của concern là gì?
Concern (ActiveSupport::Concern) là module dùng để tách và chia sẻ hành vi giữa các model/ controller, đặt trong app/models/concerns hoặc app/controllers/concerns.
# app/models/concerns/archivable.rb
module Archivable
extend ActiveSupport::Concern
included do
scope :active, -> { where(archived_at: nil) }
validates :name, presence: true
end
class_methods do
def archive_old! = where("created_at < ?", 1.year.ago).update_all(archived_at: Time.current)
end
def archive! = update!(archived_at: Time.current)
def archived? = archived_at.present?
end
class Post < ApplicationRecord
include Archivable
end
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.