我正在尝试扩展我已编写的Ruby应用程序以使用Shoes。我有一个我已经编写的类,我希望能够使用该类的GUI。也就是说,我希望我的班级有这样的东西:
class MyClass
def draw
# draw something using Shoes
end
end
MyClass
内的另一种方法会在想要绘制内容时调用draw()
。
我尝试过几种方式,但似乎都没有。我可以在Shoes应用程序中包装整个班级。假设我想绘制一个椭圆形:
Shoes.app {
class MyClass
def draw
oval :top => 100, :left => 100, :radius => 30
end
end
}
但后来它说undefined method 'oval' for MyClass
。
我也试过这个:
class MyClass
def draw
Shoes.app {
oval :top => 100, :left => 100, :radius => 30
}
end
end
这会成功运行,但每次调用test()
时都会打开一个新窗口。
如何在实例方法中使用Shoes绘制内容?
答案 0 :(得分:4)
Shoes.app { ... }
执行代码块的instance_eval。这意味着块的主体被执行就好像self是Shoes
的实例(或者它在引擎盖下使用的任何类)。你想要做的是如下:
class MyClass
def initialize(app)
@app = app
end
def draw
@app.oval :top => 100, :left => 100, :radius => 30
end
end
Shoes.app {
myclass = MyClass.new(self) # passing in the app here
myclass.draw
}
答案 1 :(得分:1)
您可以做的是将GUI与绘图分开。每次打开新窗口的原因是每次调用draw方法时都会调用Shoes.app。
试试这个:
class MyClass
def draw
oval :top => 100, :left => 100, :radius => 30
end
def test
draw
end
end
Shoes.app do
myclass = MyClass.new
myclass.test
end