module ActiveModel::Attributes::Normalization::ClassMethods
def normalize_value_for(name, value)
User.normalize_value_for(:email, " CRUISE-CONTROL@EXAMPLE.COM\n")
end
normalizes :email, with: -> email { email.strip.downcase }
attribute :email, :string
include ActiveModel::Attributes::Normalization
include ActiveModel::Attributes
class User
==== Examples
Normalizes a given +value+ using normalizations declared for +name+.
def normalize_value_for(name, value) type_for_attribute(name).cast(value) end
def normalizes(*names, with:, apply_to_nil: false)
user.email # => "cruise-control@example.com"
user.email = " CRUISE-CONTROL@EXAMPLE.COM\n"
user = User.new
end
normalizes :phone, with: -> phone { phone.delete("^0-9").delete_prefix("1") }
normalizes :email, with: -> email { email.strip.downcase }
attribute :phone, :string
attribute :email, :string
include ActiveModel::Attributes::Normalization
include ActiveModel::Attributes
class User
==== Examples
Defaults to +false+.
* +:apply_to_nil+ - Whether to apply the normalization to +nil+ values.
its sole argument, and returns it normalized.
* +:with+ - Any callable object that accepts the attribute's value as
==== Options
behavior can be changed with the +:apply_to_nil+ option.
By default, the normalization will not be applied to +nil+ values. This
should have the same result as applying it only once.
_idempotent_. In other words, applying the normalization more than once
Because the normalization may be applied multiple times, it should be
is applied when the attribute is assigned or validated.
Declares a normalization for one or more attributes. The normalization
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