Chris Carter and I threw together a simple gem to help create nested hierarchies (without relying on constructors). Sample usage: require 'lay' car = Car.lay( :color => "Red", :driver => Driver.lay( :name => "Bob" ) ) Is anyone aware of something out there that already does this (in Ruby)? Note that in the above example Car and Driver might not have constructors defined. As you've probably guessed the example simply instantiates a Car, sets its 'color' attr to "Red", and sets its 'driver' attr to a new Driver instance (whose 'name' attr is set to "Bob"). The idea was largely borrowed from groovy. I've used the groovy way of doing this extensively and have found it to be particularly useful in test cases, when you need to construct nested objects to use as test input. Please let us know if we're reinventing the wheel. Otherwise, please do a "gem install lay" and try it out and give us feedback if you think it might be useful to you. Other features: - Also pass parameters to constructors - Car.lay( ["Jetta", "V6"], :color => "Red" ) - Set member vars that don't have attr's defined - Car.lay( :_color => "Red" ) - This sets the @color member variable - We should probably change it to use :@color instead of :_color --Craig
on 2007-06-24 22:48
on 2007-06-25 07:29
Craig Muth wrote: > Chris Carter and I threw together a simple gem to help create nested > hierarchies (without relying on constructors). Sample usage: > > require 'lay' > car = Car.lay( :color => "Red", :driver => Driver.lay( :name => "Bob" ) ) There looks to be overlap with Mocha (http://mocha.rubyforge.org/classes/Mocha/AutoVerif...), though, judging from your "Other features" section, not 100%.
on 2007-06-25 19:53
> There looks to be overlap with Mocha > (http://mocha.rubyforge.org/classes/Mocha/AutoVerif...), > though, judging from your "Other features" section, not 100%. Thanks for the tip. I might have overlooked something but it seems the overlap is more in application than in functionality (meaning they differ functionally but can both be applied to creating objects for test cases). The lay() method creates instances of the target class and sets its attr's, whereas it looks like Mocha's stub and mock methods create anonymous objects, or modify or add methods to existing classes/objects. The lay() method can be fairly useful outside of test cases, as a shorthand for constructing objects that don't have convenient constructors (ie to avoid having code like: f = Foo.new; f.bar = "hey"; f.whatever = "hi"). Mocha primarily adds methods to Test::Unit::TestCase, whereas lay adds the lay() method to Class. Mocha does look pretty nice though. I'll probably make use of it for creating mock objects etc.. --Craig