Scoped Struct: Feel the Tingle
posted by pete on January 29th, 2008
Unspace’s own Mike Ferrier has a gem announcement to make. Scoped Struct is a delicious morsel of meta-programming magic designed to help you organize the functionality of Ruby classes. You can now provide access to a group of related methods using association-style syntax.
Mike uses the example of a class representing an NFL player to illustrate the concept. In a vanilla class, you might see:
class Player
def fumbles_dropped; end
def fumbles_lost; end
def fumbles_recovered; end
def passes_attempted; end
def passes_completed; end
def passes_incomplete; end
def pass_completion_percentage; end
end
However, with scoped_struct, you could re-organize like this:
class Player
scope :fumbles do
def dropped; end
def lost; end
def recovered; end
end
scope :passes do
def attempted; end
def completed; end
def incomplete; end
def completion_percentage; end
end
end
You can then access your methods like this:
my_player.passes.attempted
my_player.passes.completed
my_player.fumbles.recovered
Pretty neat, huh? It’s just a gem install scoped_struct away.
January 30th, 2008 at 02:34 PM
Very cute. Never seen this before.
February 5th, 2008 at 01:26 PM
Great job deleting the negative comments
February 6th, 2008 at 03:41 PM
What about ostruct objects containing ostruct objects ?
February 6th, 2008 at 05:08 PM
law of demeter anyone?
February 6th, 2008 at 05:41 PM
This violates several OO principles. Follow the discussion on the TorRor group:
http://groups.google.com/group/torror/browse_thread/thread/9ad31a8a3f43ff45 http://groups.google.com/group/torror/browse_thread/thread/4fd39630ef6a1334
February 9th, 2008 at 09:37 PM
Thanks for the nice piece. It’s too bad there are those who seem to get stuck on the examples and those who think CS discipline doesn’t grow or adapt to circumstances and that exceptions never arise. Too bad there are those who get caught up and miss simply appreciating someone’s effort and generosity. Thanks again.
February 21st, 2008 at 04:09 AM
Your OO violation has been reported!
:)
I really like it!!!
December 24th, 2008 at 12:31 PM
“This violates several OO principles.” => Translation to English: “This slaughters several OO sacred cows.”