在方法定义之外定义实例变量 (ruby)
我正在为 Ruby Gosu 库开发(嗯,至少尝试)一个游戏框架。我制作了一个基本的事件系统,其中每个 Blocks::Event 都有一个处理程序列表,当事件被触发时,会调用这些方法。目前实现事件的方法如下:
class TestClass
attr_accessor :on_close
def initialize
@on_close = Blocks::Event.new
end
def close
@on_close.fire(self, Blocks::OnCloseArgs.new)
end
end
但是这种实现事件的方法似乎相当长,我的问题是,我怎样才能找到一种方法,以便当有人想要在类中发生事件时,他们可以这样做
class TestClass
event :on_close
def close
@on_close.fire(self, Blocks::OnCloseArgs.new)
end
end
谢谢提前,呃。
I am developing (well, trying to at least) a Game framework for the Ruby Gosu library. I have made a basic event system wherebye each Blocks::Event has a list of handlers and when the event is fired the methods are called. At the moment the way to implement an event is as follows:
class TestClass
attr_accessor :on_close
def initialize
@on_close = Blocks::Event.new
end
def close
@on_close.fire(self, Blocks::OnCloseArgs.new)
end
end
But this method of implementing events seems rather long, my question is, how can I make a way so that when one wants an event in a class, they can just do this
class TestClass
event :on_close
def close
@on_close.fire(self, Blocks::OnCloseArgs.new)
end
end
Thanks in advance, ell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下内容完全未经测试,但也许它可以帮助您入门:
根据 Banister 的评论进行编辑。
The following is completely untested, but maybe it gets you started:
Edited according to banister's comment.
我不完全理解您要做什么,但您可以通过以下方式避免使用
initialize
方法:||=
习惯用法让您可以延迟初始化ruby 中的实例变量。I don't entirely understand what you're trying to do, but you can avoid using the
initialize
method in the following way:The
||=
idiom lets you lazily initialize instance variables in ruby.