跳至内容 跳至搜索
方法
N

实例公共方法

normalize_value_for(name, value)

使用为 name 声明的规范化方法来规范化给定的 value

示例

class User
  include ActiveModel::Attributes
  include ActiveModel::Attributes::Normalization

  attribute :email, :string

  normalizes :email, with: -> email { email.strip.downcase }
end

User.normalize_value_for(:email, " CRUISE-CONTROL@EXAMPLE.COM\n")
# => "cruise-control@example.com"
# File activemodel/lib/active_model/attributes/normalization.rb, line 134
def normalize_value_for(name, value)
  type_for_attribute(name).cast(value)
end

normalizes(*names, with:, apply_to_nil: false)

为一个或多个属性声明一个规范化。规范化在属性被赋值或验证时应用。

由于规范化可能会被应用多次,因此它应该是幂等的。换句话说,多次应用规范化应该与只应用一次的结果相同。

默认情况下,不会将规范化应用于 nil 值。可以通过 :apply_to_nil 选项更改此行为。

选项

  • :with - 任何可调用对象,它接受属性值作为其唯一参数,并返回其规范化后的值。

  • :apply_to_nil - 是否将规范化应用于 nil 值。默认为 false

示例

class User
  include ActiveModel::Attributes
  include ActiveModel::Attributes::Normalization

  attribute :email, :string
  attribute :phone, :string

  normalizes :email, with: -> email { email.strip.downcase }
  normalizes :phone, with: -> phone { phone.delete("^0-9").delete_prefix("1") }
end

user = User.new
user.email =    " CRUISE-CONTROL@EXAMPLE.COM\n"
user.email # => "cruise-control@example.com"

User.normalize_value_for(:phone, "+1 (555) 867-5309") # => "5558675309"
# File activemodel/lib/active_model/attributes/normalization.rb, line 111
def normalizes(*names, with:, apply_to_nil: false)
  decorate_attributes(names) do |name, cast_type|
    NormalizedValueType.new(cast_type: cast_type, normalizer: with, normalize_nil: apply_to_nil)
  end

  self.normalized_attributes += names.map(&:to_sym)
end