ruby-on-railsvirtus

Ruby's Virtus gem vs attr_accessor


I am looking at the Virtus gem used in a few tutorials about Service object in Ruby. In the github page, https://github.com/solnic/virtus, it gives the following example.

Using Virtus with Classes

You can create classes extended with Virtus and define attributes:

class User   include Virtus.model
  attribute :name, String   
  attribute :age, Integer   
  attribute :birthday, DateTime 
end

user = User.new(:name => 'Piotr', :age => 31) user.attributes # => { :name => "Piotr", :age => 31, :birthday => nil }

user.name # => "Piotr"

user.age = '31' # => 31 user.age.class # => Fixnum

user.birthday = 'November 18th, 1983' # => #<DateTime: 1983-11-18T00:00:00+00:00 (4891313/2,0/1,2299161)>

# mass-assignment user.attributes = { :name => 'Jane', :age => 21 } user.name # => "Jane" user.age  # => 21

I can see how the example works, but would like to understand how is this different than just defining attr_accessors in Ruby? If I have to explain to someone, the benefit of including the Virtus gem and what it does in a couple of lines, what would it be?


Solution

  • The goals of Virtus can be summarized as trying to make attributes a little more "Rails-y". They provide support for parsing form/JSON, encapsulation while retaining type information, and a few other things it's not impossible to get regular attributes to do, but not easy either.

    The real benefits, however, come when you combine Virtus with ActiveModel::Validations per this post. Since your basic values have become more responsive to the expectations of Rails form helpers, you have a very powerful alternative to nested forms.