Take a look at the valuable library.
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. 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 type casting ( '3' + '3' is not the same as 3+3)
- allow default values
From the Readme, Here's an example of its usage. I'm having an odd issue with blogger, so excuse the inheritance symbol:
class BaseballPlayer : Valuable::Base
has_value :at_bats, :klass => Integer
has_value :hits, :klass => Integer
has_value :jersey, :klass => Jersey, :default => 'unknown'
has_value :league, :default => 'unknown'
has_value :name
has_collection :teammates
def roi
hits/at_bats.to_f 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, :at_bats => 20)
>> joe.at_bats
=> 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.
0 comments:
Post a Comment