it's Valuable -- like attr_accessor on steriods

By: Johnathon Wright on: January 30, 2009

Take a look at the "ruby gem named valuable":http://valuable.mustmodify.com

I recently worked on a Rails project where most of the domain-related data came from a HyperCube database, rather than a relational one. I have to admint, albeit begrudgingly, that it provided a lot of value. Conversely, the interface was crazily complicated, and incorporating non-relational data with Rails was at best incrediby painful.

One "feature" of the hypercube was that we didn't ever get a complete schema. Data was provided when it was available, and when it wasn't available, it just didn't exist. For instance, a category might have a collection of items. If there were no items, there was no empty collection.

We needed a dry way to model the parts of the data we were using. We also wanted to be able to transparently ignore any other data that might unexpectedly appear. Finally, for my own sanity, I wanted it to feel as much like a rails model as possible.

Goals: * dry class decorators * generate getters and setters for each attribute * generate a class-level list of the attributes we handled * provide an instance-level attribute hash like Rails  * optionally provide light-weight type casting ( '3' + '3' is not the same as 3+3) * allow default values

From the Readme, Here's an example of its usage.

---ruby class BaseballPlayer < Valuable::Base   hasvalue :atbats, :klass => Integer    hasvalue :hits, :klass => Integer   hasvalue :jersey, :klass => Jersey, :default => 'unknown'   hasvalue :league, :default => 'unknown'   hasvalue :name    has_collection :teammates

  def roi      hits/atbats.tof if hits&&at_bats    end end

class Jersey < String    def initialize(object)    super "Jersey Number #{object}"   end end

joe = BaseballPlayer.new(:name => 'Joe', :hits => 5, :atbats => 20) joe.atbats => 20 joe.league => 'unknown' joe.roi=> 0.25 joe.at_bats = nil joe.roi=> nil joe.teammates=> [] joe.jersey => 'unknown' joe.jersey = 20

'Jersey Number 20'

This has also come in handy with the Flix4r code I've been writing... more about that soon.



Back