hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Erb Caching in a Handful #

by why in inspect

Dr. Eric Hodel has a brief class for caching compiled ERb templates. The compiled templates aren’t stored on the filesystem—it’s not that kind of cache. It caches the template in an instance variable to prevent recompiling if you’re reusing a template.

Of particular interest to some of you might be his use of method_missing, which our goopy red hands are continually poking around in the dark for.

 def method_missing(action, options = {})
   super unless self.respond_to? "run_#{action}" 

   options.each do |attr, value|
     self.class.send :attr_accessor, attr unless self.respond_to? attr
     self.send "#{attr}=", value
   end

   return self.send("run_#{action}")
 end

Hmm. You’ve got some self.class.send and some self.send. I really think this is an excellent fourteen lines of code for you kids who just got here. Any newbs want to take a stab at explaining?

said on 18 Apr 2005 at 23:48

Ooooh, and here I was doing [instance||class]_eval.

said on 19 Apr 2005 at 08:00

  self.class.send :attr_accessor, attr unless self.respond_to? attr

This executes in context of the class and defines an accessor for attr unlessobject already has a method ‘attr’ If where written like:

  self.send :attr_accessor, attr #...

It would call method ‘attr_accessor’ with argument ‘attr’ on the object.
said on 19 Apr 2005 at 08:12

I think doing self.class.send is a bad idea in this case as it won’t allow you to have multiple ERb cache instances that work independently of each other. It’s another case for our good friend, the meta class.

said on 19 Apr 2005 at 19:42

And with flgr’s comment, I suddenly get the metaclass .

Comments are closed for this entry.