This is a partial extraction of the DataMapper Property API with various modifications and improvements. The goal is to provide a common API for defining attributes on a model so all ORMs/ODMs could use it instead of reinventing the wheel all over again. It is also suitable for any other usecase where you need to extend your ruby objects with attributes that require data type coercions.
$ gem install virtus or in your Gemfile
gem'virtus'You can create classes extended with virtus and define attributes:
classUserincludeVirtusattribute:name,Stringattribute:age,Integerattribute:birthday,DateTimeenduser=User.new(:name=>'Piotr',:age=>28)user.attributes# =>{:name => "Piotr", :age => 28 }user.name# => "Piotr"user.age='28'# => 28user.age.class# => Fixnumuser.birthday='November 18th, 1983'# => #<DateTime: 1983-11-18T00:00:00+00:00 (4891313/2,0/1,2299161)># mass-assignmentuser.attributes={:name=>'Jane',:age=>21}user.name# => "Jane"user.age# => 21You can create modules extended with virtus and define attributes for later inclusion in your classes:
moduleNameincludeVirtusattribute:name,StringendmoduleAgeincludeVirtusattribute:age,IntegerendclassUserincludeName,Ageenduser=User.new(:name=>'John',:age=>'30')It's also possible to dynamically extend an object with Virtus:
classUser# nothing hereenduser=User.newuser.extend(Virtus)user.attribute:name,Stringuser.name='John'user.name# => 'John'classPageincludeVirtusattribute:title,String# default from a singleton value (integer in this case)attribute:views,Integer,:default=>0# default from a singleton value (boolean in this case)attribute:published,Boolean,:default=>false# default from a callable object (proc in this case)attribute:slug,String,:default=>lambda{ |page,attribute| page.title.downcase.gsub(' ','-')}# default from a method name as symbolattribute:editor_title,String,:default=>:default_editor_titledefdefault_editor_titlepublished? ? title : "UNPUBLISHED: #{title}"endendpage=Page.new(:title=>'Virtus README')page.slug# => 'virtus-readme'page.views# => 0page.published# => falsepage.editor_title# => "UNPUBLISHED: Virtus README"classCityincludeVirtusattribute:name,StringendclassAddressincludeVirtusattribute:street,Stringattribute:zipcode,Stringattribute:city,CityendclassUserincludeVirtusattribute:name,Stringattribute:address,Addressenduser=User.new(:address=>{:street=>'Street 1/2',:zipcode=>'12345',:city=>{:name=>'NYC'}})user.address.street# => "Street 1/2"user.address.city.name# => "NYC"# Support "primitive" classesclassBookincludeVirtusattribute:page_numbers,Array[Integer]endbook=Book.new(:page_numbers=>%w[123])book.page_numbers# => [1, 2, 3]# Support EmbeddedValues, too!classAddressincludeVirtusattribute:address,Stringattribute:locality,Stringattribute:region,Stringattribute:postal_code,StringendclassPhoneNumberincludeVirtusattribute:number,StringendclassUserincludeVirtusattribute:phone_numbers,Array[PhoneNumber]attribute:addresses,Set[Address]enduser=User.new(:phone_numbers=>[{:number=>'212-555-1212'},{:number=>'919-444-3265'}],:addresses=>[{:address=>'1234 Any St.',:locality=>'Anytown',:region=>"DC",:postal_code=>"21234"}])user.phone_numbers# => [#<PhoneNumber:0x007fdb2d3bef88 @number="212-555-1212">, #<PhoneNumber:0x007fdb2d3beb00 @number="919-444-3265">]user.addresses# => #<Set:{#<Address:0x007fdb2d3be448 @address="1234 Any St.", @locality="Anytown", @region="DC", @postal_code="21234">}>classPackageincludeVirtusattribute:dimensions,Hash[Symbol=>Float]endpackage=Package.new(:dimensions=>{'width'=>"2.2",:height=>2,"length"=>4.5})package.dimensions# =>{:width => 2.2, :height => 2.0, :length => 4.5 }Virtus performs coercions only when a value is being assigned. If you mutate the value later on using its own interfaces then coercion won't be triggered.
Here's an example:
classBookincludeVirtusattribute:title,StringendclassLibraryincludeVirtusattribute:books,Array[Book]endlibrary=Library.new# This will coerce Hash to a Book instancelibrary.books=[{:title=>'Introduction to Virtus'}]# This WILL NOT COERCE the value because you mutate the books array with Array#<<library.books << {:title=>'Another Introduction to Virtus'}A suggested solution to this problem would be to introduce your own class instead of using Array and implement mutation methods that perform coercions. For example:
classBookincludeVirtusattribute:title,StringendclassBookCollection < Arraydef <<(book)ifbook.kind_of?(Hash)super(Book.new(book))elsesuperendendendclassLibraryincludeVirtusattribute:books,BookCollection[Book]endlibrary=Library.newlibrary.books << {:title=>'Another Introduction to Virtus'}classGeoLocationincludeVirtus::ValueObjectattribute:latitude,Floatattribute:longitude,FloatendclassVenueincludeVirtusattribute:name,Stringattribute:location,GeoLocationendvenue=Venue.new(:name=>'Pub',:location=>{:latitude=>37.160317,:longitude=> -98.437500})venue.location.latitude# => 37.160317venue.location.longitude# => -98.4375# Supports object's equalityvenue_other=Venue.new(:name=>'Other Pub',:location=>{:latitude=>37.160317,:longitude=> -98.437500})venue.location === venue_other.location# => trueVirtus comes with a builtin coercion library. It's super easy to add your own coercion classes. Take a look:
require'digest/md5'# Our new attribute typeclassMD5 < Virtus::Attribute::ObjectprimitiveStringcoercion_method:to_md5end# Defining the Coercion methodmoduleVirtusclassCoercionclassString < Virtus::Coercion::Objectdefself.to_md5(value)Digest::MD5.hexdigestvalueendendendend# And now the user!classUserincludeVirtusattribute:name,Stringattribute:password,MD5enduser=User.new(:name=>'Piotr',:password=>'foobar')user.name# => 'Piotr'user.password# => '3858f62230ac3c915f300c664312c63f'require'json'moduleMyApp# Defining the custom attribute(s)moduleAttributesclassJSON < Virtus::Attribute::ObjectprimitiveHashdefcoerce(value) ::JSON.parsevalueendendendclassUserincludeVirtusattribute:info,Attributes::JSONendenduser=MyApp::User.newuser.info='{"email":"john@domain.com"}'# =>{"email"=>"john@domain.com"}user.info.class# => Hash- Dan Kubb (dkubb)
- Chris Corbyn (d11wtq)
- Emmanuel Gomez (emmanuel)
- Fabio Rehm (fgrehm)
- Ryan Closner (rclosner)
- Markus Schirp (mbj)
- Yves Senn (senny)
- Fork the project.
- Make your feature addition or bug fix.
- Add tests for it. This is important so I don't break it in a future version unintentionally.
- Commit, do not mess with Rakefile or version (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
- Send me a pull request. Bonus points for topic branches.
Copyright (c) 2011-2012 Piotr Solnica
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


