Auto-coerced virtual attributes with Virtus

Posted Over 10 years ago. Visible to the public.

We've since created ActiveType Show archive.org snapshot which has a restricted subset of Virtus' features. It might be enough for your needs.

We sometimes give our ActiveRecord models virtual attributes Show archive.org snapshot for values that don't need to be stored permanently.

When such a virtual attribute should contain integer values you might get unexpected behavior with forms, because every param is a string and you don't get the magic type casting that Rails would give you if it was an actual database column. E.g. when you set an ActiveRecord date field to '10.05.2011' it will automatically parse that to a Date instance, and when you set it to an empty string, it will set the field to nil. This auto-casting of assigned values is called coercion.

Losing automatic coercion is not merely an inconvenience, it can also lead to bugs in your application. E. g. when you are storing integers without coercion, and you have form roundtrips due to validation errors, <select> boxes "forget" their values because all params are strings and "123" does not match 123.

A wonderful way to get virtual attributes with full coercion magic is to use Virtus Show archive.org snapshot :

class User < ActiveRecord::Base
  include Virtus.model(:constructor => false)
  
  attribute :name, String
  attribute :age, Integer
  attribute :birthday, DateTime  
end

You can now say:

user = User.new
user.age = '65'
user.age # => 65
user.birthday = '17.11.1982'
user.birthday => DateTime<#...>

Note how we had to include Virtus with the :constructor => false option so it doesn't overwrite the initializer provided by ActiveRecord. Also note that Virtus can be used in any Ruby class (not just ActiveRecord), and in other cases an auto-generated Virtus constructor might be a nice thing to have.

Checkout out the Virtus README Show archive.org snapshot for its many, many wonderful features.

Henning Koch
Last edit
About 10 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-12-19 09:33)