How to call Shoes methods from inside an instance

2019-07-20 14:17发布

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?

标签: ruby shoes
2条回答
对你真心纯属浪费
2楼-- · 2019-07-20 14:31

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
查看更多
趁早两清
3楼-- · 2019-07-20 14:34

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
}
查看更多
登录 后发表回答