问题
Is there any way to access an outer method from inside a class? For example:
Using a .haml file ( therefore inside class Haml::Engine), have a class Tumblr defined, with a method self.render. Outside of the Tumblr class, #haml_concat functions perfectly, but returns a NameError inside Tumblr. #haml_concat is defined in Haml::Helpers. Why is #haml_concat unusable inside Tumblr?
value = 42
class TestClass
def test_method
value
end
end
TestClass.new.value
# should ideally return 42
Right now this just returns NameError: undefined local variable or method 'value' for #<TestClass:0x00000000e24960>.
回答1:
If you don't specify receiver of the method, ruby looking it in the class of the current object and up to all its ancestors.
So, because Haml::Engine is not in the list of Tumblr ancestors, ruby can't find this method. The solution is to specify object on which you calling method explicitly.
And, do you really define Tumblr class inside haml file? It looks like a very bad approach.
来源:https://stackoverflow.com/questions/10627566/access-outer-method-from-inside-class