How to call Shoes methods from inside an instance method?

不打扰是莪最后的温柔 提交于 2019-12-12 18:17:33

问题


I am trying to extend a Ruby application I've already written to use Shoes. I have a class that I've already written and I want to be able to use a GUI with that class. That is, I want my class to have something like this:

class MyClass
   def draw
    # draw something using Shoes
  end
end

Another method inside MyClass will call draw() when it wants to draw something.

I've tried doing this in several ways and none of them seem to work. I could wrap the entire class in a Shoes app. Let's say I want to draw an oval:

Shoes.app {
  class MyClass
    def draw
      oval :top => 100, :left => 100, :radius => 30
    end
  end
}

But then it says undefined method 'oval' for MyClass.

I also tried this:

class MyClass
  def draw
    Shoes.app {
      oval :top => 100, :left => 100, :radius => 30
    }
  end
end

This runs successfully but it opens a new window every time test() is called.

How can I draw things using Shoes from inside an instance method?


回答1:


Shoes.app { ... } does an instance_eval of the code block. What that means is the that the body of the block gets executed as though self were an instance of Shoes (or whatever class it is using under the hood). What you'll want to do is something like the following:

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
}



回答2:


What you can do is separate the GUI from the drawing. The reason a new windows is opened every time is that Shoes.app is called everytime the draw method is called.

Try this:

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


来源:https://stackoverflow.com/questions/4575850/how-to-call-shoes-methods-from-inside-an-instance-method

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