From: Christopher Dicely Date: 2008-03-06T00:50:47+09:00 Subject: Re: Meta Programming Question On Wed, Mar 5, 2008 at 2:35 AM, MohsinHijazee wrote: > > On Mar 5, 1:19 pm, Rubén Medellín wrote: > > On Mar 5, 1:51 am, MohsinHijazee wrote: > > > > > Hello! > > > > > Consider this case: > > > > > myHash = {:a_line_of_code => "pre_count = Posts.count", > > > :another_line => %q~message = > > > get_formatted_message(#{pre_count})~} > > > > > If I have a hash like this which contains code snippets as strings, > > > How can I execute them? Moreover consider also that the second code > > > snippet uses the value of the variable assigned in the first one. > > > > > Regards, > > > Mohsin > > > > If you need to use a variable from a hash maybe you should be using it > > outside the hash context. What I mean is that probably you shouldn't > > be putting a variable there. > > You can always use eval to execute strings, but may not be a great > > idea. > > > > In any case, you may use procs instead of storing variables if what > > you want is dynamically generated values for the hash. > > > > >> hash = {:something => proc{ Posts.count }, :other_thing => proc{|var| do_something_with(var)}} > > > > and you could call > > > > >> hash[:other_thing][hash[:something]] > > > > but the ugliness of that cries desperately for a more elegant way. If > > you need to execute code, I think there is a feature or Ruby called > > errr, methods. > > > > Could you give more details of what you are trying? > > I am actually trying to automat the testing of an existing Rails > application > to the point where I only specify that what function to be tested with > what > params and what to expect in the response. Some of the functions being > tested > change the state of the system that's why its necessary to calcuate > some of > the system stats before executing the test call to that function and > after the > test call and then to check the before and after responses to validate > that > the call really made the change to the system. Here is the structure > (yet rough) to > list all the tests in the system which would be automatically > executed. Is there a reason that Test::Unit (with appropriate setup and teardown for the test cases) won't work? If it does, that would be better than reinventing the wheel. If it doesn't, knowing what limitation you hit with that might help people propose an appropriate solution.