Reply to comment
Data-izing arbitrary attributes, the lazy way
Posted August 22nd, 2009 at 2:52 pmFor the Cedar Falls Poker website, there's a stats page in which a particular model is hit pretty hard. There used to be a series of methods handling the retrieval of data in a useful manner, but I standardized the way this happens so I could clean up the model code and make it more useful.
This uses Hashes to return data in a format that is easy to turn into pie charts or bar graphs. This code assumes a few things. It assumes you do not have any other methods with _data in the name. It assumes that you're only going to be pulling data that is available as a method or attribute call; namely, using send. If your classes aren't set up this way, they probably should be.
class << self def data(atr) returning(Hash.new(0)) do |h| all.each do |rec| h[rec.send(atr)] += 1 end end end def method_missing(meth, *attrs) if meth.to_s.match(/(\w+)\_data/) data($1) end end end
And, as an example of how you might use this:
# assume we have a 'Game' model with an attribute called 'kind' and an attribute called 'structure' a = Game.structure_data # => calls data('structure') b = Game.kind_data # => calls data('kind') p a #=> { 'No Limit' => 5, 'Pot Limit' => 6, 'Tournament' => 2 } p b #=> { 'Cash' => 11, 'Tournament' => 2 }
The key represents the attribute, and the value represents the number of records in the table that have that value for that attribute.
Rails does stuff like this a lot, but it's nice to see how simple it is to provide such flexible functionality. Note that if you are not using this in Rails, you might have to rewrite the data method to avoid using returning, and find an alternative to using 'all'.
Recent comments
1 sec ago
1 min ago
8 min 52 sec ago
13 min 14 sec ago
14 min 43 sec ago
15 min 52 sec ago
30 min 30 sec ago
31 min 6 sec ago
37 min 20 sec ago
41 min 36 sec ago