[ruby on rails] concerns的使用

  • concern是用来把公共的方法提取到一起,保持代码DRY,是用module来实现的

model中的concern

ruby 复制代码
module Visible
  extend ActiveSupport::Concern

  VALID_STATUSES = ['public', 'private', 'archived']  # 其他地方引用  Visible::VALID_STATUSES
 
  # 关联关系 blongs_to, has_many 、validates、 scope 都需要写到 included block中
  included do
    belongs_to :user

    validates :status, inclusion: { in: VALID_STATUSES }
    validate do
      errors[:name] << '请输入名称' if name.to_s.splict(',').size < 2
    end
    
    scope :public_count, -> { where(status: 'public').count }
    
    # 类方法一
    def self.public_count
      where(status: 'public').count
    end
    
    # 类方法二
    class << self
      def public_count
        where(status: 'public').count
      end
    end
     
	# 实例方法
    def public?
      status == 'public'
    end
  end
  
  # 类方法三,写到 included 外面
  class_methods do
    def public_count
      where(status: 'public').count
    end
  end

  # 实例方法
  def archived?
    status == 'archived'
  end
end
相关推荐
canonical_entropy15 小时前
AI时代,我们还需要低代码吗?—— 一场关于模型、演化与软件未来的深度问答
后端·低代码·aigc
颜如玉15 小时前
HikariCP:Dead code elimination优化
后端·性能优化·源码
考虑考虑16 小时前
Jpa使用union all
java·spring boot·后端
用户25191624271116 小时前
Python之语言特点
python
bobz96517 小时前
virtio vs vfio
后端
刘立军17 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
Rexi17 小时前
“Controller→Service→DAO”三层架构
后端
bobz96518 小时前
计算虚拟化的设计
后端
深圳蔓延科技18 小时前
Kafka的高性能之路
后端·kafka
Barcke18 小时前
深入浅出 Spring WebFlux:从核心原理到深度实战
后端