Fraser
Fraser

Reputation: 1521

Access outer method from inside class

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

Upvotes: 0

Views: 226

Answers (1)

Flexoid
Flexoid

Reputation: 4245

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.

Upvotes: 2

Related Questions