ruby-on-rails - 如何将参数传递到 before_save 钩子中的模块?
问题描述
我有一个模块:
# frozen_string_literal: true
# will strip whitespace of certain attributes
module StripWhitespace
extend ActiveSupport::Concern
included do
before_save :strip_whitespace
end
# Strips white space from these user attributes
def strip_whitespace(attrs)
attrs.each do |attr|
self[attr] = send(attr)&.strip
end
end
end
我目前将其包含在模型中:
class User < ApplicationRecord
include StripWhitespace
end
但是,我希望能够将参数传递给before_save
钩子。像这样的东西:
# user.rb
COLS_TO_STRIP = %i[first_name last_name location phone city]
before_save strip_whitespace(COLS_TO_STRIP)
这两种方式都行不通。作为 ruby 的新手,我不确定我是否正确执行此操作。我应该在模型中这样做吗?还是模块?我的模块设置正确吗?
解决方案
参数可以通过如下回调钩子传递 -
before_save -> { strip_whitespace(COLS_TO_STRIP) }
推荐阅读
- rest-assured - 从 Rest Assured 响应中提取嵌套值
- php - PHP 使用带有 google QR 码 api 的变量
- selenium - 如何在 iframe 中找到隐藏的 UI 元素
- c# - 如何使用 GLFW.Net 初始化 OpenGL.NET?
- math - 如何减小球体中心点和点 P 之间的半径并找到点 P 的新坐标?
- javascript - Angular找到一个类型的所有服务
- sql - 内部连接中的案例条件
- android - 如何从 Flutter 访问设备应用程序
- python - Python Pandas 数据框 - 组合/合并具有空值的行
- c - Ghidra 使用像“._0_4_”这样的奇怪字段名称来表示 C 反编译中的非默认访问大小