开发者

How to call Shoes methods from inside an instance method?

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
  开发者_StackOverflow中文版    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?


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
}


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜