Friday, 12 December 2014

12 Tips of Christmas - 2 Virtus

2. Use Virtus in your form objects

I love form objects. Stripping away unwanted complexity in our models and housing them in nice neat little packages of code is amazing. Virtus gives me a little extra boost by doing alot of the coercions of my form attributes for me, allowing me to just get on with building the functionality I need. 
To get started, simply plug the virtus gem in your gemfile, and inside your form object (let's say its one of my favourites, a report) add the following:
class UserForm
  include Virtus.model

  attribute :joined_on, Date

  attribute :username, String
end
Now when I initialize the object with a params hash, I don't have to think about getters and setters, or cooercing Dates or DateTimes, I can just pass the params in and have Virtus do the hard work for me. 


No comments:

Post a Comment