How to call Training methods from an instance method?

I am trying to extend a Ruby application I already wrote to use Shoes. I have a class that I have already written and I want to be able to use a GUI with this 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 be called draw()

when it wants to draw something.

I've tried to do this in multiple ways and none of them seem to work. I could wrap the whole 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 he speaks 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 succeeds, but test()

a new window opens on every call .

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

+2


source to share


2 answers


Shoes.app { ... }

contains an instance of an instance of a code block. This means the block body is executed as if I were an instance Shoes

(or whatever class it uses under the hood). What you want to do is something like this:



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
}

      

+4


source


What you can do is separate the GUI from the drawing. The reason new windows open every time is because Shoes.app is called every time the draw method is called.

Try the following:



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

      

+1


source







All Articles