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>
.
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 ofTumblr
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.