Access outer method from inside class

旧街凉风 提交于 2019-12-23 06:24:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!