Add new types to Rails 5 attributes API

The Rails 5 attributes API allows us to build form objects very easily.

I had previously been using an after_initialize callback to downcase emails, with the following code I can define an :email date type and values are automatically cast when set.

This has the advantage of casting subsequent calls to set the email value.

class EmailType < ActiveModel::Type::String
  def cast(value)
    return super unless value.is_a?(String)
    super(value.downcase)
  end
end

ActiveModel::Type.register(:email, EmailType)


class Foo
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :email, :email
end


> Foo.new(email: 'EMAIL@MAIL.com').email
=> 'email@mail.com'


1
Joe

Get our stories delivered

From us to your inbox weekly.