Skip to Content Skip to Search

module ActiveModel::Attributes::Normalization::ClassMethods

Public instance methods

Normalizes a given value using normalizations declared for name.

Examples

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"
Source code GitHub
# File activemodel/lib/active_model/attributes/normalization.rb, line 134
def normalize_value_for(name, value)
  type_for_attribute(name).cast(value)
end

Declares a normalization for one or more attributes. The normalization is applied when the attribute is assigned or validated.

Because the normalization may be applied multiple times, it should be idempotent. In other words, applying the normalization more than once should have the same result as applying it only once.

By default, the normalization will not be applied to nil values. This behavior can be changed with the :apply_to_nil option.

Options

  • :with - Any callable object that accepts the attribute’s value as its sole argument, and returns it normalized.

  • :apply_to_nil - Whether to apply the normalization to nil values. Defaults to false.

Examples

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"
Source code GitHub
# 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

Definition files