On 6/19/07, Mark Somerville <ms / pccl.info> wrote: > I'm confused, to say the least! I'm setting up caches on objects using a > class variable. My rule of thumb is, Do Not Use Class Variables, use Class Instance Variables It all works well until I try to extract it out to a module > to mixin to other objects: > > module HostBasedCache > def setup_cache(method, &method_proc) > @@cache_method = method_proc if block_given? > class_eval <<-METHOD > def self.#{method}(param) > #some stuff not relevant > puts @@cache_method.call(param) > #some stuff not relevant > end > METHOD > end > end > > class MyObject > > extend HostBasedCache > setup_cache(:find_with_roles) do |id| > User.find_by_id(id, :select => "users.id, roles.id", :include => [ :roles > ]) > end > > end > > Unfortunately, when calling find_with_roles I'm told that @@cache_method > isn't defined. Setting @@cache_method explicitly in MyObject (rather than the > setup_cache) call makes everything work. I must be missing some scoping > problem - can anyone explain this to me, please? > Look at this slightly adapted code just using Class Instance Variables. Does this solve your problem? -------------------------8<---------------------------- module HostBasedCache def setup_cache(method, &method_proc) @cache_method = method_proc if block_given? class_eval <<-METHOD def self.#{method}(param) #some stuff not relevant puts @cache_method.call(param) #some stuff not relevant end METHOD end end class MyObject extend HostBasedCache setup_cache(:find_with_roles) do |id| # User.find_by_id(id, :select => "users.id, roles.id", :include => [ :roles ]) puts "Hi there " << id.to_s end end MyObject.find_with_roles( 42 ) -------------------------8<---------------------------- Cheers Robert -- You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw