Wynn Netherland changelog.com/posts

Virtus - give your Ruby objects DataMapper-like attributes

I’ve written a few wrappers for various JSON APIs, and each time I’ve had to make a decision about how to represent API data in Ruby. Ruby hashes and arrays work well but bracket[‘notation’], can be hard on the eyes and fingers. My go-to library for these types of objects is often Hashie, the hash toolkit from Intridea. Its Mash, Dash, Clash, and Trash, objects provide some syntactic sugar on top of Ruby’s Hash.

Thanks to Mike’s linkblog, another project has caught my eye. Virtus from Piotr Solnica extracts DataMapper’s Property API, for the times when you need to implement attributes on your objects yet maintain a bit more encapsulation. I love the module approach for defining properties:

module Name
  include Virtus

  attribute :name, String
end

module Age
  include Virtus

  attribute :age, Integer
end

class User
  include Name, Age
end

user = User.new(:name => 'John', :age => '30')

Check the excellent README or source on GitHub for more.


Discussion

Sign in or Join to comment or subscribe

Player art
  0:00 / 0:00