When I call self.class.instance_variable_set("@var", ...)
from inside a class method, where is that variable actually stored? Is it on the class itself? On the instance of that class? I can't seem to find it with any of the following:
e = Example.new
e.instance_variables
e.class.class_variables
I even tried using the (class <<开发者_如何学编程; self; self; end)
trick but I can't find anything (http://ruby-metaprogramming.rubylearning.com/html/seeingMetaclassesClearly.html).
Here is the code snippet (which works as I need) but I'm not sure why it works :)
module HandyModule
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def use_template(template_name)
self.class.instance_variable_set("@_template", template_name)
end
def build(attributes = {})
template_name = self.class.instance_variable_get("@_template")
# do stuff with the template
end
end
end
class Example
include HandyModule
use_template :contact_form
end
Essentially I can include this handy module, and then I have a class method called use_template
with which I can specify which template to be used by my build method.
When you call use_template
inside the class definition, the self
is the class Example
. When you call self.class
, it is Example.class
, or Class
. You define the instance variable to the class of the classes.
class Class
p @_template
end
# prints :contact_form
You probably should use just self
instead of self.class
.
精彩评论