如何在Ruby类定义内部调用基于ActiveSupport::Concern的自定义方法
实现ActiveRecord自定义行为模块,支持指定字段生成Scope和Validation
核心实现代码
先定义基于ActiveSupport::Concern的自定义模块,把配置方法放到ClassMethods中,确保模型include后能直接调用:
require 'active_support/concern' module MyCustomBehavior extend ActiveSupport::Concern module ClassMethods # 接收任意数量的字段参数,为每个字段生成增强逻辑 def my_custom_behavior(*fields) fields.each do |field| # 生成非空查询Scope scope "with_#{field}_present".to_sym, -> { where.not(field => nil) } # 生成非空验证规则 validates_presence_of field, message: "#{field} 不能为空" # 可按需扩展更多逻辑,比如针对邮箱的格式验证 # validates_format_of field, with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i, if: -> { field == :email } end end end end
在模型中使用
include模块后,直接调用my_custom_behavior指定需要增强的字段即可:
class User < ApplicationRecord include MyCustomBehavior # 为name和email字段批量生成Scope和验证 my_custom_behavior :name, :email end
效果验证
- Scope调用:执行
User.with_name_present会生成WHERE "users"."name" IS NOT NULL的查询语句 - 验证生效:创建空值的User实例时,
user.valid?返回false,user.errors.full_messages会输出["Name 不能为空", "Email 不能为空"]
原理说明
ActiveSupport::Concern会自动把ClassMethods里的方法注入到include该模块的模型类中,所以模型定义阶段能直接调用my_custom_behavior- 通过可变参数
*fields接收多个字段,遍历字段动态生成对应的Scope和验证规则,实现批量增强
内容的提问来源于stack exchange,提问作者aarona
相关产品推荐
相关产品推荐

