例如
class Foo
def bar
end
end
在该代码中,bar只能在类的任何实例中使用。
是否可以将方法的执行上下文更改为Eigenclass
,而不更改方法本身的定义方式,从而使该方法现在可以作为单例使用,而无需调用self.new
?
最好是,我想对通过Foo
可以继承的类添加的代码执行任何这样的代码。
目前我正在做的事情相当于:
class Test
def method_added method
self.define_singleton_method method do
self.new.send method
end
end
end
出于我的需要,这不起作用,因为我正在通过调用new
来更改执行上下文。
您可以简单地执行:
class Test
def self.method_added method
module_function method
end
end
class A < Test
def foo
:hello
end
end
A.foo #=> :hello
我刚刚想好了怎么做>_<。
这是代码:
class Test
def method_added method
m = self.new.method(method) #get method object
self.define_singleton_method(method) do #create method with same name within the singleton class
m.call #call the block which will now run the code of the added method within the context of the Eigenclass/Singleton
end
end
end
因此,它所做的是从实例中获取一个方法对象,然后将该方法作为类上下文中的块来调用。
因此,第一个代码示例变成:
class Foo < Test
def bar
end
end
并且方法CCD_ 5现在可以被访问为CCD_ 6而不是CCD_ 7,这意味着不创建实例;除了它在添加的方法中所做的时间之外,但这很好,因为据我所知,这是获取方法对象的唯一方法。
这就是为什么当类被继承时(在def self.inherited
中),最好只创建一次实例,将其存储在类中,然后只访问它,而不是调用self.new
。