Attributes on Steroids for Plain Old Ruby Objects
require 'virtus'
class User
include Virtus.model
attribute :id, Integer
attribute :experience, Array[Experience]
end
class Experience
include Virtus.model
attribute :begin_date, String
attribute :end_date, String
attribute :title, String
def duration
[begin_date, end_date]
end
end
I have two dates:
[Experience[begin_date: '2010-10-20', end_date'2012-03-24'], Experience[begin_date: '2010-04-01', end_date: '2012-01-20']]
I need this to distinguish first and last year of user experience history.
def experience_years
first_job_date = experience.map(&:begin_date).compact.sort.first
last_job_date = experience.map(&:end_date).compact.sort.last
last_job_date.year - first_job_date.year + 1 if first_job_date && last_job_date
end
I thought about using virtus collections like here:
class BookCollection < Array
def <<(book)
if book.kind_of?(Hash)
super(Book.new(book))
else
super
end
end
end
class Library
include Virtus.model
attribute :books, BookCollection[Book]
end
But I am not sure how to do it.
Source: (StackOverflow)