Access outer method from inside class

2019-06-08 22:26发布

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

标签: ruby scope
1条回答
戒情不戒烟
2楼-- · 2019-06-08 23:18

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.

查看更多
登录 后发表回答