首页 > 解决方案 > 如何将参数传递到 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​​ 的新手,我不确定我是否正确执行此操作。我应该在模型中这样做吗?还是模块?我的模块设置正确吗?

标签: ruby-on-railsruby

解决方案


参数可以通过如下回调钩子传递 -

before_save -> { strip_whitespace(COLS_TO_STRIP) }

推荐阅读