2

我正在尝试扩展我已经编写的 Ruby 应用程序以使用 Shoes。我有一个已经编写好的类,我希望能够在该类中使用 GUI。也就是说,我希望我的班级有这样的东西:

class MyClass
   def draw
    # draw something using Shoes
  end
end

当它想要绘制一些东西时,内部的另一个方法MyClass会调用。draw()

我已经尝试过几种方法,但它们似乎都不起作用。我可以将整个班级包装在一个鞋子应用程序中。假设我想画一个椭圆:

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 绘制东西?

4

2 回答 2

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
}
于 2011-01-01T22:22:22.840 回答
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
于 2011-01-01T22:01:54.277 回答