---
title: "Add new types to Rails 5 attributes API"
description: "The Rails 5 attributes API allows us to build form objects very easily."
canonical: https://oozou.com/til/add-new-types-to-rails-5-attributes-api-13
locale: en
date: 2020-10-13
topic: ruby-on-rails
---

# Add new types to Rails 5 attributes API

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

Published: 2020-10-13 · Topic: [ruby on rails](https://oozou.com/til-topics/ruby-on-rails) ([markdown](https://oozou.com/til-topics/ruby-on-rails.md))

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.

```ruby
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)
```

```ruby
class Foo
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :email, :email
end
```

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

---

Contact OOZOU: hello@oozou.com · +66 2544 0000 · https://oozou.com/contact

More for AI agents: https://oozou.com/llms.txt · every page has a markdown twin at its URL plus ".md"
