Reply to comment

Data-izing arbitrary attributes, the lazy way

For 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.

  1. class << self
  2. def data(atr)
  3. returning(Hash.new(0)) do |h|
  4. all.each do |rec|
  5. h[rec.send(atr)] += 1
  6. end
  7. end
  8. end
  9.  
  10. def method_missing(meth, *attrs)
  11. if meth.to_s.match(/(\w+)\_data/)
  12. data($1)
  13. end
  14. end
  15. end

And, as an example of how you might use this:

  1. # assume we have a 'Game' model with an attribute called 'kind' and an attribute called 'structure'
  2. a = Game.structure_data # => calls data('structure')
  3. b = Game.kind_data # => calls data('kind')
  4.  
  5. p a #=> { 'No Limit' => 5, 'Pot Limit' => 6, 'Tournament' => 2 }
  6. 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'.

Reply

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <java>, <javascript>, <php>, <rails>, <ruby>, <scheme>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
5 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.